Ejemplo n.º 1
0
Archivo: client.py Proyecto: wezu/a4p
    def __init__(self):
        log.debug('Starting Client')
        #open a window... but first set all the needed props
        wp = self.loadWindoProperites()
        #open the window
        base.openMainWindow(props=wp)
        #base.setBackgroundColor(0.06, 0.1, 0.12, 1)
        base.setBackgroundColor(0.0, 0.0, 0.0, 1)
        base.disableMouse()
        base.enableParticles()

        #needed to determine what window event fired
        self.window_focused = base.win.getProperties().getForeground()
        self.window_x = base.win.getXSize()
        self.window_y = base.win.getYSize()
        self.window_minimized = base.win.getProperties().getMinimized()

        #filter manager, post process
        self.filters = Filters()

        #audio sound effects (sfx) + music
        self.audio = Audio()
        self.audio.setMusic('background')
        self.audio.playMusic()

        #light manager
        self.lights = LightManager()

        #setup the user interface (gui+key/mouse bind)
        self.ui = UserInterface()

        #skybox
        self.sun_and_sky = Skybox(self.lights)

        #player (character) droid
        self.droid = PCDroid(self.ui)

        #some vars used later
        self.map_name = None
        self.loading_status = set()
        self.level_root = render.attachNewNode('level_root')
        self.level_root.hide()
        self.is_in_game = False

        #events
        base.win.setCloseRequestEvent('exit-event')
        self.accept('exit-event', self.onClientExit)
        self.accept('window-event', self.onWindowEvent)
        self.accept('window-reset', self.onWindowReset)
        self.accept('client-mouselock', self.setMouseLock)
        self.accept('load-level', self.onLevelLoad)
        self.accept('loading-done', self.onLoadingDone)
        self.accept('reload-shaders', self.onShaderReload)
        self.accept('client-set-team', self.onTeamCahnge)
        self.accept('client-quit', self.onQuit)
        # Task
        taskMgr.add(self.update, 'client_update')

        log.debug('Client started')
Ejemplo n.º 2
0
 def __init__(self):
     self.ui = UserInterface(self)
     self.svg = None
     self.geojson = None
     self.layer_output = []
     self.bounds = [0.0, 0.0, 0.0, 0.0]
     self.rotation = 0.0
     self.last_click = None
     self.ui.run()
Ejemplo n.º 3
0
 def __init__(self):
     # Game Objects
     self.pl = Player()
     self.map = Map()
     self.ph = PlayerHandler()
     self.eh = EnemyHandler()
     self.game_name = "test"
     self.ui = UserInterface(ph=self.ph,
                             eh=self.eh,
                             defDir=str("~/rtgm/games/" + self.game_name))
    def getAll():
        conn = sqlite3.connect('savedPasswords.db')
        c = conn.cursor()

        ui.clearScreen()
        print(ui.Screen['viewAllPasswordsScreen']['header'])

        for row in c.execute("SELECT * FROM passwords ORDER BY date"):
            print(row)

        c.close()
        conn.close()
        input("Hit any Key to proceed...")
    def save(password):
        today = time.strftime("%m/%d/%Y")

        conn = sqlite3.connect('savedPasswords.db')
        c = conn.cursor()

        ui.clearScreen()
        name = input("What Name would you like to store this password as?\n\n")
        ui.clearScreen()
        username = input(
            "What Username (if any), would you like to save with this password?\n\n"
        )
        ui.clearScreen()
        print(ui.Screen['verifySaveScreen']['header'])
        ui.innerSpace(8)
        print("Date: " + today)
        print("Name: " + name)
        print("Username: "******"Password: "******"CREATE TABLE IF NOT EXISTS passwords (date TEXT, name TEXT, username TEXT, password TEXT)"
            )
            c.execute(
                "INSERT INTO passwords (date,name,username,password) VALUES (?,?,?,?)",
                (today, name, username, password))
            conn.commit()
            c.close()
            conn.close()
        elif (choice == 2):
            Database.save(password)
        else:
            c.close()
            conn.close()
            quit()
Ejemplo n.º 6
0
def main():

    def gracefulExit():
        ui.killAllThreads()
        root.destroy()
    
    settings = Settings()
    settings.writeSettings()

    root = Tk()

    root.geometry("{0}x{1}+0+0".format(root.winfo_screenwidth(), root.winfo_screenheight()))
    root.wm_overrideredirect(True)
    root.wm_overrideredirect(1)
    root.wm_attributes("-topmost", True)
    root.wm_attributes("-transparentcolor", "white")
    root.config(bg='white')

    
    api = API(settings)
    log = ReadLogFile(root, settings)

    log.reopenLogfile()

    inv = Inventory(settings, api)
    chaos = Chaos(settings, inv, log)

    ui = UserInterface(root, settings, inv, api, chaos, log)

    Button(root, text="Quit", command = gracefulExit, anchor=N).place(x=root.winfo_screenwidth()/2, y=root.winfo_screenheight()-30)

    root.mainloop()
Ejemplo n.º 7
0
def main(wnd):
    global terminate
    if len(sys.argv) > 1:
        tag = sys.argv[1]
    else:
        tag = 'activity/work-background'
    ui = UserInterface(wnd)
    yar = YandexRadio(tag, ui)
    pl = Player()

    lastplayed = None
    queue = []
    while not pl.terminate:
        if len(queue) == 0:
            queue = yar.gettracks(lastplayed)

        curtrack = queue[0]
        queue = queue[1:]
        info = curtrack[2]
        # dur = curtrack[3]
        batch = curtrack[4]
        curtrack = curtrack[:2]
        pl.play(yar, curtrack, info, batch)
        lastplayed = curtrack
    yar.save_cookies()
Ejemplo n.º 8
0
Archivo: client.py Proyecto: wezu/a4p
    def __init__(self):
        log.debug('Starting Client')
        #open a window... but first set all the needed props
        wp=self.loadWindoProperites()
        #open the window
        base.openMainWindow(props = wp)
        #base.setBackgroundColor(0.06, 0.1, 0.12, 1)
        base.setBackgroundColor(0.0, 0.0, 0.0, 1)
        base.disableMouse()
        base.enableParticles()

        #needed to determine what window event fired
        self.window_focused=base.win.getProperties().getForeground()
        self.window_x=base.win.getXSize()
        self.window_y=base.win.getYSize()
        self.window_minimized=base.win.getProperties().getMinimized()

        #filter manager, post process
        self.filters=Filters()

        #audio sound effects (sfx) + music
        self.audio=Audio()
        self.audio.setMusic('background')
        self.audio.playMusic()

        #light manager
        self.lights=LightManager()

        #setup the user interface (gui+key/mouse bind)
        self.ui=UserInterface()

        #skybox
        self.sun_and_sky=Skybox(self.lights)

        #player (character) droid
        self.droid=PCDroid(self.ui)

        #some vars used later
        self.map_name=None
        self.loading_status=set()
        self.level_root=render.attachNewNode('level_root')
        self.level_root.hide()
        self.is_in_game=False

        #events
        base.win.setCloseRequestEvent('exit-event')
        self.accept('exit-event',self.onClientExit)
        self.accept( 'window-event', self.onWindowEvent)
        self.accept( 'window-reset', self.onWindowReset)
        self.accept( 'client-mouselock', self.setMouseLock)
        self.accept( 'load-level', self.onLevelLoad)
        self.accept( 'loading-done', self.onLoadingDone)
        self.accept( 'reload-shaders', self.onShaderReload)
        self.accept( 'client-set-team', self.onTeamCahnge)
        self.accept( 'client-quit', self.onQuit)
        # Task
        taskMgr.add(self.update, 'client_update')

        log.debug('Client started')
Ejemplo n.º 9
0
    def __init__(self, money, health, morale):
        # Initialize renderer first because it starts SDL
        self.renderer = Renderer()

        self.textures = Textures()
        self.textures.load(self.renderer.sdl_renderer)

        self.user_interface = UserInterface(self.textures)
        self.controller = Controller()
        self.entities = Entities()

        self.entities.init_player(0, 0, self.textures.get(TextureType.PLAYER),
                                  money, health, morale)

        world_creator = WorldCreator(2)
        self.entities.map_rectangle = world_creator.create(
            self.entities, self.textures)
Ejemplo n.º 10
0
 def __init__(self):
     self.ui = UserInterface()
     self.cryp = Al(self.ui)
     self.addCommandForUI()
     self.isThread = False
     self.stop_event = threading.Event()
     self.algThread = None
     self.ui.root.protocol("WM_DELETE_WINDOW", self.stopProgram)
Ejemplo n.º 11
0
    def __init__(self):
        # Create the QApplication first so that QThread, QTimer, etc. can be used
        self.qt_app = QApplication()
        self.qt_app.aboutToQuit.connect(self.quit)

        self.database_connection = DatabaseConnection(self)
        self.user_interface = UserInterface(self)

        self.qt_app.exec_()
Ejemplo n.º 12
0
 def __init__(self, fileinfo, n_connections = 30):
     self.fileinfo = fileinfo
     self.n_connections = n_connections
     self.pieces =  [FilePiece(idx, sha1, fileinfo) for idx, sha1 in enumerate(fileinfo.pieces)]
     self.peers = []
     self.queue = Queue()
     self.ui = UserInterface(self.fileinfo.total_size)
     self.server = peer.PeerServer(6880, self.fileinfo)
     self.filesystem_manager = FilesystemManager(self.fileinfo)
     #start with wrong estimate
     self.piece_freq = [1] * len(self.pieces)
    def searchDB(name):
        conn = sqlite3.connect('savedPasswords.db')
        c = conn.cursor()

        ui.clearScreen()
        print(ui.Screen['findPasswordScreen']['header'])
        ui.innerSpace(2)

        for row in c.execute("SELECT * FROM passwords WHERE name=?", (name, )):
            print(row)

        ui.innerSpace(15)

        c.close()
        conn.close()
        input("Hit any Key to proceed...")
Ejemplo n.º 14
0
 def uiTest(self):
     # self.plSetup()
     self.ui = UserInterface(ph=self.ph, eh=self.eh)
     self.ui.UILoop()
Ejemplo n.º 15
0
def main(filename="", new_database=False, echo=False):
    """Connects to database and insert dummy data."""
    if new_database:
        db = UserInterface(filename, new_db=True, echo=echo)
        print("Making new database file and inserting dummy data...")

        countries = [{
            "name": "Poland"
        }, {
            "name": "France"
        }, {
            "name": "Germany"
        }]
        [db.add_object(Country, country) for country in countries]

        locations = [{
            "street": "Wielka",
            "postal_code": "50-100",
            "city": "Lublin",
            "country_name": "Poland"
        }, {
            "street": "Angielska",
            "postal_code": "50-101",
            "city": "Lublin",
            "country_name": "Poland"
        }]
        [db.add_object(Location, location) for location in locations]

        jobs = [{
            "title": "Manager",
            "min_salary": "3000",
            "max_salary": "5000"
        }, {
            "title": "Driver",
            "min_salary": "1000",
            "max_salary": "4000"
        }]
        [db.add_object(Job, job) for job in jobs]

        employees = [{
            "first_name": "Jan",
            "last_name": "Nowak",
            "email": "*****@*****.**",
            "phone_number": "60 825 23 38",
            "hire_date": "12.12.12",
            "job_id": "1",
            "salary": "2000",
            "department_id": "1"
        }, {
            "first_name": "Andrzej",
            "last_name": "Lisiecki",
            "email": "*****@*****.**",
            "phone_number": "512 650 222",
            "hire_date": "13.12.12",
            "job_id": "2",
            "manager_id": "1",
            "salary": "1500",
            "department_id": "2"
        }]
        [db.add_object(Employee, employee) for employee in employees]

        departments = [{
            "name": "Office",
            "manager_id": "1",
            "location_id": 1
        }, {
            "name": "Warehouse",
            "manager_id": "1",
            "location_id": 2
        }, {
            "name": "Shop",
            "manager_id": "1",
            "location_id": 2
        }]
        [db.add_object(Department, department) for department in departments]

        db.ui_loop()
    else:
        db = UserInterface("employees.db")
        db.ui_loop()
Ejemplo n.º 16
0
class Game:
    def __init__(self):
        # Game Objects
        self.pl = Player()
        self.map = Map()
        self.ph = PlayerHandler()
        self.eh = EnemyHandler()
        self.game_name = "test"
        self.ui = UserInterface(ph=self.ph,
                                eh=self.eh,
                                defDir=str("~/rtgm/games/" + self.game_name))

    # def __del__(self):
    # self.pl = None
    # self.map = None
    # self.mh = None
    # self.ph = None
    # self.ui = None

    def mapSetup(self):
        self.map.setV("name", "earth")
        self.map.setV(
            "msg",
            "This planet is named Earth. There are many mysteries that lie inside of this planet. "
        )
        # self.ph.mh.map = self.map
        self.ph.mh.loadMap("earth.json")

    def plSetup(self):
        from pc import PlayerCreator
        plc = PlayerCreator()
        plc.createLoop()
        self.pl = plc.pl
        self.ph = PlayerHandler(self.pl)

    def createEnemy(self):
        return Enemy(name="goblin", mhp=100, atk=8, pdef=4, spd=10)

    def uiTest(self):
        # self.plSetup()
        self.ui = UserInterface(ph=self.ph, eh=self.eh)
        self.ui.UILoop()

    def enemySetup(self):
        enemy = self.createEnemy()
        self.eh = EnemyHandler(enemy)

    def battleTest(self):
        battle = Battle(self.ph, self.eh)
        battle.battleLoop()

    def storeSetup(self):
        store = Store(name="Shop", des="Just an average shop")
        store.get("inventory")["items"].append(
            Item(name="testitem", des="This item is test item."))
        sh = StoreHandler(self.ph, store)
        sh.storeLoop()

    def inventorySetup(self):
        inventory = InventoryHandler(self.ph)
        inventory.inventoryLoop()
Ejemplo n.º 17
0
from devices import SENSOR
from ui import UserInterface
from machine import RTC
from utime import localtime
from themes import *
rtc = RTC()
print("Synchronize time from NTP server ...")
rtc.ntp_sync(server="0.ua.pool.ntp.org", tz="Europe/Kiev")
while not rtc.synced():
    sleep_ms(100)
    break

collect()

theme = indigo
ui = UserInterface(theme)
sensor = SENSOR()

while KeyboardInterrupt:
    _raw_time = localtime()
    _date = str(_raw_time[2]) + '/' + str(_raw_time[1]) + '/' + str(
        _raw_time[0])
    _time = "{:0>2}".format(_raw_time[3] + 2) + ":{:0>2}".format(_raw_time[4])
    ui.mem_free_label(mem_free())
    ui.temp_label(sensor.temperature)
    ui.humi_label(sensor.humidity)
    ui.pres_label(sensor.pressure)
    ui.time_label(_time)
    collect()
    sleep(0.5)
Ejemplo n.º 18
0
def main():

    r1 = Receptionist(id=1)
    r2 = Receptionist(id=2)
    ch1 = Chair(_id=1)
    ch2 = Chair(_id=2)
    statistics = Statistics()

    r_list = [r1, r2]
    ch_list = [ch1, ch2]

    p1 = Patient(id=1,
                 hp=85,
                 name="Patric",
                 receptionists=r_list,
                 chairs=ch_list,
                 statistics=statistics)
    p2 = Patient(id=2,
                 hp=93,
                 name="Danil",
                 receptionists=r_list,
                 chairs=ch_list,
                 statistics=statistics)
    p3 = Patient(id=3,
                 hp=30,
                 name="Bernard",
                 receptionists=r_list,
                 chairs=ch_list,
                 statistics=statistics)
    p4 = Patient(id=4,
                 hp=41,
                 name="Stefan",
                 receptionists=r_list,
                 chairs=ch_list,
                 statistics=statistics)
    p5 = Patient(id=5,
                 hp=12,
                 name="Carl",
                 receptionists=r_list,
                 chairs=ch_list,
                 statistics=statistics)
    p6 = Patient(id=6,
                 hp=92,
                 name="Joe",
                 receptionists=r_list,
                 chairs=ch_list,
                 statistics=statistics)
    p7 = Patient(id=7,
                 hp=55,
                 name="Anna",
                 receptionists=r_list,
                 chairs=ch_list,
                 statistics=statistics)

    p_list = [p1, p2, p3, p4, p5, p6, p7]

    coffee1 = CoffeeMachine(id=1)
    coffee2 = CoffeeMachine(id=2)
    surgeryRoom1 = SurgeryRoom(id=1)
    surgeryRoom2 = SurgeryRoom(id=2)

    coffee_list = [coffee1, coffee2]
    surgery_rooms = [surgeryRoom1, surgeryRoom2]

    d1 = Doctor(id=1,
                name="Dr Nowacka",
                energy_points=35,
                chairs=ch_list,
                location=Location.CORRIDOR,
                coffee_machines=coffee_list,
                surgery_rooms=surgery_rooms)
    d2 = Doctor(id=2,
                name="Dr Kowalski",
                energy_points=15,
                chairs=ch_list,
                location=Location.CORRIDOR,
                coffee_machines=coffee_list,
                surgery_rooms=surgery_rooms)
    d3 = Doctor(id=3,
                name="Dr Wozniak",
                energy_points=5,
                chairs=ch_list,
                location=Location.CORRIDOR,
                coffee_machines=coffee_list,
                surgery_rooms=surgery_rooms)
    d4 = Doctor(id=4,
                name="Profesor Kowalczyk",
                energy_points=45,
                chairs=ch_list,
                location=Location.CORRIDOR,
                coffee_machines=coffee_list,
                surgery_rooms=surgery_rooms)
    d5 = Doctor(id=5,
                name="Dr Wojtasik",
                energy_points=65,
                chairs=ch_list,
                location=Location.CORRIDOR,
                coffee_machines=coffee_list,
                surgery_rooms=surgery_rooms)

    doctor_list = [d1, d2, d3, d4, d5]

    interface = UserInterface(chairs=ch_list,
                              coffee_machines=coffee_list,
                              doctors=doctor_list,
                              patients=p_list,
                              receptionists=r_list,
                              surgery_rooms=surgery_rooms)

    patient_manager = Patient_Finished(patients=p_list,
                                       receptionists=r_list,
                                       chairs=ch_list,
                                       statistics=statistics)

    for doctor in doctor_list:
        doctor.start()

    for patient in p_list:
        patient.start()

    patient_manager.start()
    interface.start()

    killer = threading.Thread(target=killer_run,
                              args=(p_list, doctor_list, patient_manager,
                                    interface))
    killer.start()
    killer.join()

    for doctor in doctor_list:
        doctor.join()

    for patient in p_list:
        patient.join()

    patient_manager.join()
    interface.join()
def main():

    chosen_menu = 'q'
    ui = UserInterface()
    ui.clear_sreen()

    while chosen_menu != '0':
        ui.show_main_menu()
        chosen_menu = ui.choose_menu_number()

        if chosen_menu == "1":
            # Create the necessary instances
            create_and_upload_table = CreateTable()
            generate_applicants = ApplicantGenerator(
                "example_data/applicant.txt")
            ui.clear_sreen()
            chosen_administrator_menu = 'q'

            while chosen_administrator_menu != "0":
                ui.show_administrator_menu()
                chosen_administrator_menu = ui.choose_submenu_number(
                    "Administrator")

                if chosen_administrator_menu == "1":
                    try:
                        create_and_upload_table.create_table()
                        ui.show_generetad_data("Tables", False)
                    except:
                        ui.show_cant_generate_data("tables")

                elif chosen_administrator_menu == "2":
                    try:
                        create_and_upload_table.generate_example_data()
                        ui.show_generetad_data("Example data")
                    except:
                        ui.show_cant_generate_data("example data")

                elif chosen_administrator_menu == "3":
                    try:
                        generate_applicants.generate_applicant()
                        ui.show_generetad_data("Applicants data")
                    except:
                        ui.show_cant_generate_data("applicants data")

                elif chosen_administrator_menu == "4":
                    try:
                        generate_applicants.generate_nearest_school()
                        generate_applicants.generate_interview_for_applicants()
                        ui.show_generetad_data("Interview dates")
                    except:
                        ui.show_cant_generate_data("interviews date")

                elif chosen_administrator_menu == "0":
                    ui.clear_sreen()
                    break

                else:
                    ui.show_wrong_number()

        elif chosen_menu == "2":
            mentor_details = MentorDetails()
            ui.clear_sreen()
            chosen_mentor_menu = 'q'

            while chosen_mentor_menu != "0":
                ui.show_mentor_menu()
                chosen_mentor_menu = ui.choose_submenu_number("Mentor")

                if chosen_mentor_menu == '1':
                    try:
                        mentor_details.mentor_date_time()
                    except:
                        ui.show_cant_found("mentor id")

                elif chosen_mentor_menu == '0':
                    ui.clear_sreen()
                    break
                else:
                    ui.show_wrong_number()

        elif chosen_menu == '3':
            # Create instances
            applicant_detail = ApplicantDetails()
            ui.clear_sreen()
            chosen_applicant_menu = 'q'

            while chosen_applicant_menu != '0':
                ui.show_applicant_menu()
                chosen_applicant_menu = ui.choose_submenu_number("Applicant")

                if chosen_applicant_menu == '1':
                    try:
                        applicant_detail.interview_details()
                    except:
                        ui.show_cant_found("applicant code")

                elif chosen_applicant_menu == '2':
                    try:
                        applicant_detail.status_details()
                    except:
                        ui.show_cant_found("applicant code")

                elif chosen_applicant_menu == '3':
                    try:
                        applicant_detail.school_details()
                    except:
                        ui.show_cant_found("applicant code")

                elif chosen_applicant_menu == '0':
                    ui.clear_sreen()
                    break

                else:
                    ui.show_wrong_number()

        elif chosen_menu == '0':
            ui.show_say_hello()
        else:
            ui.show_wrong_number()
Ejemplo n.º 20
0
from board import Board
from ui import UserInterface
from game import Game
from tests import Test as TestClass

if __name__ == "__main__":
    TranslationTable = {0: " ", 1: "E", 2: "*", 3: "X", 4:"-"}
    Test = TestClass()
    Test.TestFire()
    Grid = Board(TranslationTable)
    _Game = Game(Grid)
    _Game.GridSetup()
    UI = UserInterface(Grid, _Game)
    UI.Start()
Ejemplo n.º 21
0
class TorrentDownloader(object):
    def __init__(self, fileinfo, n_connections = 30):
        self.fileinfo = fileinfo
        self.n_connections = n_connections
        self.pieces =  [FilePiece(idx, sha1, fileinfo) for idx, sha1 in enumerate(fileinfo.pieces)]
        self.peers = []
        self.queue = Queue()
        self.ui = UserInterface(self.fileinfo.total_size)
        self.server = peer.PeerServer(6880, self.fileinfo)
        self.filesystem_manager = FilesystemManager(self.fileinfo)
        #start with wrong estimate
        self.piece_freq = [1] * len(self.pieces)

    def connect_to_peers(self):
        for p in self.fileinfo.get_all_peers():
            if len(self.peers) == self.n_connections:
                break
            if any(other.host == p.ip and other.port == p.port for other in self.peers):
                continue
            try:
                self.ui.update_log('connect ' + str(p))
                self.fileinfo.used_peer(p)
                self.ui.peer_connected()
                self.peers += [peer.PeerConn(self.fileinfo, self, hostport=(p.ip, p.port))]
            except socket.error as e:
                self.ui.update_log(str(e))

    def update_piece_freq(self):
        self.piece_freq = [0] * len(self.pieces)

        for otherpeer in self.peers:
            for idx, has in enumerate(otherpeer.bitfield):
                self.piece_freq[idx] += has

    def get_rarest_piece_had_by(self, peer):
        if random.randint(0, 50) == 0:
            self.update_piece_freq() #only do this occasionally to save time
        piece_id, freq = min(enumerate(self.piece_freq),
            key=lambda (i, f): f if peer.bitfield[i] and not self.pieces[i].is_fully_requested() else 99999)
        if self.pieces[piece_id].is_fully_requested():
            return None
        else:
            return self.pieces[piece_id]

    def update_choking_status(self, new_unchoke):
        if new_unchoke:
            self.ui.peer_unchoked()
        else:
            self.ui.peer_choked()

    def got_piece(self, piece_id, block_begin, data):
        self.ui.got_block(len(data))
        block_id = block_begin / BLOCK_SIZE
        piece = self.pieces[piece_id]
        piece.add_block(block_id, data)
        if piece.is_fully_downloaded():
            [p.have(piece.piece_index) for p in self.peers]
            piece.verify_and_write(self.filesystem_manager)
            self.ui.got_piece()
        if all(piece.is_fully_downloaded() for piece in self.pieces):
            self.close_all_peers()

    def got_request(self, peer, req):
        piece_index, block_offset, block_len = req
        piece = self.filesystem_manager.get_piece(FilePiece(piece_index, 0, self.fileinfo))
        if hasattr(piece, 'data'):
            block = piece.data[block_offset : block_offset + block_len]
            peer.piece(piece_index, block_offset, block)
        else:
            peer.close()

    #this algorithm is extremely simple. but it should work reasonably well.
    def interest_state(self, peer):
        if peer.peer_interested:
            if sum([not p.am_choking for p in self.peers]) < 4:
                peer.choke(False) #unchoke this peer if it's okay
            elif random.randint(0, 9) == 0:
                #sometimes, randomly choke someone else and unchoke anyway
                random.choice([p for p in self.peers if not p.am_choking]).choke(True)
                peer.choke(False)
        else:
            peer.choke(True)
            #optomistically unchoke
            random.choice([p for p in self.peers if p.am_choking]).choke(False)

    def close_all_peers(self):
        for peer in self.peers:
            peer.close()

        self.peers = []

    def get_request_to_make(self, peer):
        piece_to_get = self.get_rarest_piece_had_by(peer)
        if not piece_to_get:
            return None
        block_idx = piece_to_get.get_next_block_id()
        return piece_to_get.piece_index, block_idx * BLOCK_SIZE, BLOCK_SIZE

    def peer_closed(self, peer):
        self.ui.lost_peer(not peer.peer_choking)
        self.peers.remove(peer)
        self.connect_to_peers()

    def start(self):
        self.connect_to_peers()
        asyncore.loop()
Ejemplo n.º 22
0
Archivo: client.py Proyecto: wezu/a4p
class Client(DirectObject):
    """
    Client class handels gui/input audio and rendering
    """
    def __init__(self):
        log.debug('Starting Client')
        #open a window... but first set all the needed props
        wp = self.loadWindoProperites()
        #open the window
        base.openMainWindow(props=wp)
        #base.setBackgroundColor(0.06, 0.1, 0.12, 1)
        base.setBackgroundColor(0.0, 0.0, 0.0, 1)
        base.disableMouse()
        base.enableParticles()

        #needed to determine what window event fired
        self.window_focused = base.win.getProperties().getForeground()
        self.window_x = base.win.getXSize()
        self.window_y = base.win.getYSize()
        self.window_minimized = base.win.getProperties().getMinimized()

        #filter manager, post process
        self.filters = Filters()

        #audio sound effects (sfx) + music
        self.audio = Audio()
        self.audio.setMusic('background')
        self.audio.playMusic()

        #light manager
        self.lights = LightManager()

        #setup the user interface (gui+key/mouse bind)
        self.ui = UserInterface()

        #skybox
        self.sun_and_sky = Skybox(self.lights)

        #player (character) droid
        self.droid = PCDroid(self.ui)

        #some vars used later
        self.map_name = None
        self.loading_status = set()
        self.level_root = render.attachNewNode('level_root')
        self.level_root.hide()
        self.is_in_game = False

        #events
        base.win.setCloseRequestEvent('exit-event')
        self.accept('exit-event', self.onClientExit)
        self.accept('window-event', self.onWindowEvent)
        self.accept('window-reset', self.onWindowReset)
        self.accept('client-mouselock', self.setMouseLock)
        self.accept('load-level', self.onLevelLoad)
        self.accept('loading-done', self.onLoadingDone)
        self.accept('reload-shaders', self.onShaderReload)
        self.accept('client-set-team', self.onTeamCahnge)
        self.accept('client-quit', self.onQuit)
        # Task
        taskMgr.add(self.update, 'client_update')

        log.debug('Client started')

    def doSomeStuffTsk(self, task):
        x = deque(range(5000))
        for i in xrange(999):
            random.shuffle(x)
            #print i, x[0]
        #print 'done'
        return task.done

    def setMouseLock(self, lock):
        wp = WindowProperties.getDefault()
        if lock:
            wp.setMouseMode(WindowProperties.M_confined)
        else:
            wp.setMouseMode(WindowProperties.M_relative)
        if not cfg['use-os-cursor']:
            wp.setCursorHidden(True)
        base.win.requestProperties(wp)

    def loadWindoProperites(self):
        #check if we can open a fullscreen window at the requested size
        if cfg['fullscreen']:
            mods = []
            for mode in base.pipe.getDisplayInformation().getDisplayModes():
                mods.append([mode.width, mode.height])
            if list(cfg['win-size']) not in mods:
                cfg['fullscreen'] = False
                log.warning('Can not open fullscreen window at ' +
                            str(cfg['win-size']))

        #the window props should be set by this time, but make sure
        wp = WindowProperties.getDefault()
        try:
            wp.setUndecorated(cfg['undecorated'])
            wp.setFullscreen(cfg['fullscreen'])
            wp.setSize(cfg['win-size'][0], cfg['win-size'][1])
            wp.setFixedSize(cfg['win-fixed-size'])
        except:
            log.warning('Failed to set window properties, Traceback:')
            for error in traceback.format_exc().splitlines()[1:]:
                log.warning(error.strip())

        #these probably won't be in the config (?)
        wp.setOrigin(-2, -2)
        wp.setTitle('A4P')
        if not cfg['use-os-cursor']:
            wp.setCursorHidden(True)
        return wp

    def loadLevel(self, task):
        log.debug('Client loading level...')
        with open(path + 'maps/' + self.map_name + '.json') as f:
            values = json.load(f)
        #set the time
        self.sun_and_sky.setTime(values['level']['time'])
        #self.sun_and_sky.show()
        #load visible objects
        for id, obj in enumerate(values['objects']):
            mesh = loader.loadModel(path + obj['model'])
            mesh.reparentTo(self.level_root)
            mesh.setPosHpr(tuple(obj['pos']), tuple(obj['hpr']))
            mesh.setTag(
                'id_' + str(id), str(id)
            )  #we may need to find this mesh later to link it to a Bullet object
            for name, value in obj['shader_inputs'].items():
                if isinstance(value, basestring):
                    mesh.setShaderInput(str(name),
                                        loader.loadTexture(path + value))
                if isinstance(value, float):
                    mesh.setShaderInput(str(name), value)
                if isinstance(value, list):
                    if len(value) == 2:
                        mesh.setShaderInput(str(name),
                                            Vec2(value[0], value[1]))
                    elif len(value) == 3:
                        mesh.setShaderInput(str(name),
                                            Vec3(value[0], value[1], value[2]))
                    elif len(value) == 3:
                        mesh.setShaderInput(
                            str(name),
                            Vec4(value[0], value[1], value[2], value[3]))
            mesh.setShader(
                Shader.load(Shader.SLGLSL, obj['vertex_shader'],
                            obj['fragment_shader']))
        #set the music
        self.audio.setMusic(values['level']['music'])
        #self.level_root.prepareScene(base.win.getGsg())
        messenger.send('loading-done', ['client'])
        return task.done

    #events
    def onQuit(self):
        self.level_root.removeNode()
        self.level_root = render.attachNewNode('level_root')
        self.level_root.hide()
        if self.ui.is_zoomed:
            self.ui.zoom()
        self.sun_and_sky.hide()
        self.droid.disable()
        self.ui.unbindKeys()
        self.ui.in_game_menu.hide()
        self.ui.main_menu.show()
        self.audio.setMusic('background')
        self.loading_status = set()
        self.is_in_game = False
        messenger.send('world-clear-level')

    def onTeamCahnge(self, team):
        self.droid.setTeam(team)

    def onShaderReload(self):
        log.debug('Client: Reloading shaders')
        for mesh in self.level_root.getChildren():
            shader = mesh.getShader()
            v_shader = shader.getFilename(Shader.ST_vertex)
            f_shader = shader.getFilename(Shader.ST_fragment)
            mesh.setShader(Shader.load(Shader.SLGLSL, v_shader, f_shader))
        self.ui.main_menu.setShader(path + 'shaders/gui_v.glsl',
                                    path + 'shaders/gui_f.glsl')
        self.filters.reset()

    def onLoadingDone(self, target):
        log.debug(str(target) + ' loading done')
        self.loading_status.add(target)
        if self.loading_status == set(['client', 'server', 'world']):
            self.ui.main_menu.hide()
            self.level_root.show()
            self.sun_and_sky.show()
            self.ui.bindKeys()
            self.droid.node.setPos(render, 20, 0, 2)
            self.droid.lockCamera()
            self.droid.model.show()
            self.droid.rig.show()
            self.droid.gun.show()
            self.ui.in_game_menu.showElements('hud_')
            self.ui.hideSoftCursor()
            self.ui.is_main_menu = False
            self.is_in_game = True
            messenger.send('world-link-objects',
                           [self.droid.node, 'pc_droid_node'])

    def onLevelLoad(self, map_name):
        self.map_name = map_name
        #we wait 1.0 sec for the loading animation to finish just in case if loading takes < 1.0 sec.
        taskMgr.doMethodLater(1.0,
                              self.loadLevel,
                              'client_loadLevel_task',
                              taskChain='background_chain')
        #taskMgr.add(self.loadLevel, 'client_loadLevel_task', taskChain = 'background_chain')
        #the client needs to load/setup:
        # -visible geometry
        # -enviroment (skybox/dome + sunlight diection + fog + ???)
        # -water plane
        # -unmovable (point)light sources
        # -unmovable vfx
        # -the player droid

    def onClientExit(self):
        log.debug('Client exit')
        self.audio.cleanup()
        app.exit()

    def onWindowReset(self):
        wp = self.loadWindoProperites()
        base.win.requestProperties(wp)

    def onWindowMinimize(self):
        self.window_minimized = base.win.getProperties().getMinimized()
        log.debug('window-event: Minimize is ' + str(self.window_minimized))

    def onWindowFocus(self):
        self.window_focused = base.win.getProperties().getForeground()
        log.debug('window-event: Focus set to ' + str(self.window_focused))
        if self.is_in_game:
            self.ui.in_game_menu.showMenu(self.window_focused)
        if not self.window_focused:
            self.ui.cursor_pos = (0, 0, 0)
        if cfg['pause-on-focus-lost']:
            if not self.window_focused:
                self.audio.pauseMusic()
                base.win.setActive(False)
            else:
                self.audio.resumeMusic()
                base.win.setActive(True)

    def onWindowResize(self):
        self.window_x = base.win.getXSize()
        self.window_y = base.win.getYSize()
        log.debug('window-event: Resize')
        self.filters.update()
        self.ui.updateGuiNodes()

    def onWindowEvent(self, window=None):
        if window is not None:  # window is none if panda3d is not started
            if self.window_x != base.win.getXSize(
            ) or self.window_y != base.win.getYSize():
                self.onWindowResize()
            elif window.getProperties().getMinimized(
            ) != self.window_minimized:
                self.onWindowMinimize()
            elif window.getProperties().getForeground() != self.window_focused:
                self.onWindowFocus()

    #tasks
    def update(self, task):
        dt = globalClock.getDt()
        render.setShaderInput('camera_pos', base.cam.getPos(render))
        return task.cont
Ejemplo n.º 23
0
def main_menu():
    ui = UserInterface()

    while True:
        choice = input("""
    --------------------------------------------------
    Press 1 To Add New Stock\n
    Press 2 To Check the Current Stock\n
    Press 3 To Add Item to Cart\n
    Press 4 To Make a Purchase\n
    Press 5 To Display a Cart\n
    Press 6 To Empty a Cart\n
    Press 7 To Display all Reports\n
    Press Q to quit\n
    --------------------------------------------------

    Please enter your choice: """)
        if choice == "1":
            model = input("Please enter model")
            price = input("Please enter price")
            colour = input("Please enter colour")
            size = input("Please enter size")
            gender = input("Please enter gender")
            quantity = input("Please enter quantity")
            ui.add_new_bike(model, price, colour, size, gender,
                            quantity)  # sends arguments to the method
            print("Successfully added to stock!")
        elif choice == "2":
            ui.display_stock()
        elif choice == "3":
            ui.add_to_cart()
        elif choice == '4':
            ui.make_purchase()
        elif choice == '5':
            ui.display_cart()
        elif choice == '6':
            ui.empty_the_cart()
        elif choice == '7':
            ui.display_reports()
        elif choice == "Q" or choice == "q":
            break
        else:
            print("You must only select either 1, 2 or Q.")
            print("Please try again")
Ejemplo n.º 24
0
from question_model import Question
from data import question_data
from quiz_brain import QuizBrain
from ui import UserInterface

question_bank = []
for question in question_data:
    question_text = question["question"]
    question_answer = question["correct_answer"]
    new_question = Question(question_text, question_answer)
    question_bank.append(new_question)

quiz = QuizBrain(question_bank)
quiz_ui = UserInterface(quiz)

# while quiz.still_has_questions():
#     quiz.next_question()

print("You've completed the quiz")
print(f"Your final score was: {quiz.score}/{quiz.question_number}")
Ejemplo n.º 25
0
from time import sleep
from gc import collect, mem_free
from devices import SENSOR
from ui import UserInterface
from rgb565color import *

collect()

ui = UserInterface()
sensor = SENSOR()

while KeyboardInterrupt:
    ui.mem_free_label(mem_free(), CORAL)
    ui.temp_label(sensor.temperature, MAGENTA)
    ui.humi_label(sensor.humidity, LIME)
    ui.pres_label(sensor.pressure, GAINSBORO)
    collect()
    sleep(0.5)
Ejemplo n.º 26
0
class Controller:
    def __init__(self):
        self.ui = UserInterface(self)
        self.svg = None
        self.geojson = None
        self.layer_output = []
        self.bounds = [0.0, 0.0, 0.0, 0.0]
        self.rotation = 0.0
        self.last_click = None
        self.ui.run()

    def load_svg(self, path):
        with open(path) as file:
            svg = SVG(file.read())
            self.svg = svg
            self.geojson = GeoJSON(self.svg)
            self.layer_output = list(self.svg.get_layers())
            self.update_result()

        self.ui.load_preview(path)
        layers = self.svg.get_layers()
        self.ui.load_layers(layers)

    def set_layer_output(self, layer: str, enable: bool):
        if enable:
            self.layer_output.append(layer)
        else:
            self.layer_output.remove(layer)

    def update_boundaries(self, direction: chr, value, update_ui=True):
        if direction == 'N':
            self.bounds[0] = value
        elif direction == 'S':
            self.bounds[1] = value
        elif direction == 'E':
            self.bounds[2] = value
        elif direction == 'W':
            self.bounds[3] = value

        if update_ui:
            self.ui.set_boundaries(self.bounds)
        self.update_result()

    def update_rotation(self, rotation):
        self.rotation = rotation
        self.update_result()

    def update_result(self):
        print(
            f'Updating to match the bounds {self.bounds} with {self.rotation}º of rotation.'
        )
        geojson = self.geojson.calculate(self.layer_output, self.bounds,
                                         self.rotation)
        self.ui.set_output(geojson)
        self.ui.draw_polygons(self.geojson.polygons)

    def record_click(self, lon: float, lat: float):
        self.last_click = lon, lat
        self.ui.set_last_click(lon, lat)

    def replace_lim(self, direction: chr):
        if direction in ('N', 'S'):
            self.update_boundaries(direction, self.last_click[1])
        else:
            self.update_boundaries(direction, self.last_click[0])
Ejemplo n.º 27
0
from ui import UserInterface
from controller import Controller
from domain import Map


if __name__ == "__main__":
    ctrl = Controller()
    ui = UserInterface(ctrl)
    ui.main()
Ejemplo n.º 28
0
class Game:
    # Parameters: starting values for money, health, and morale
    def __init__(self, money, health, morale):
        # Initialize renderer first because it starts SDL
        self.renderer = Renderer()

        self.textures = Textures()
        self.textures.load(self.renderer.sdl_renderer)

        self.user_interface = UserInterface(self.textures)
        self.controller = Controller()
        self.entities = Entities()

        self.entities.init_player(0, 0, self.textures.get(TextureType.PLAYER),
                                  money, health, morale)

        world_creator = WorldCreator(2)
        self.entities.map_rectangle = world_creator.create(
            self.entities, self.textures)

    def run(self):
        running = True

        # For average FPS calculation
        frames = 0
        last_frame = sdl2.SDL_GetTicks()

        # Display splash screen
        while sdl2.SDL_GetTicks() < last_frame\
        + Renderer.splash_screen_display_time:
            self.renderer.render_splash_screen(self.textures)

        # Game loop:
        while running:
            # 1. Handle input from the user interface
            screen_dimensions = [
                self.renderer.screen_width, self.renderer.screen_height
            ]
            running = self.user_interface.handle_input(self.controller,
                                                       screen_dimensions)

            # 2. Update entities from the controller
            self.controller.update_entities(self.entities)
            self.controller.generate_NPCs(self.entities, self.textures)
            # if not self.controller.check_player_meters(self.entities):
            if self.controller.current_health <= 0 or self.controller.current_morale <= 0:
                # Display splash screen
                last_frame = sdl2.SDL_GetTicks()
                while sdl2.SDL_GetTicks() < last_frame\
                + Renderer.splash_screen_display_time:
                    self.renderer.render_lose_screen(self.textures)
                running = False

            # 3. Update screen from the renderer
            self.renderer.render(self.entities, self.textures,
                                 self.user_interface, screen_dimensions)

            # For debugging:
            # Average FPS for performance profiling, prints every 5 seconds
            frames += 1
            if sdl2.SDL_GetTicks() - last_frame > 5000:
                print('Average FPS: ' + str(frames / 5.0))
                frames = 0
                last_frame = sdl2.SDL_GetTicks()

        self.close()

    def get_renderer(self):
        """Returns the game renderer that was instantiated by the game class
		so that it can be used in other components that need to borrow from it.
		"""

        return self.renderer

    def get_textures(self):
        """Returns the game textures that were instantiated by the game class
		so that they can be used by other components.
		"""

        return self.textures

    # Closes the game renderer
    def close(self):
        self.textures.unload()
        self.renderer.close()
Ejemplo n.º 29
0
Archivo: client.py Proyecto: wezu/a4p
class Client(DirectObject):
    """
    Client class handels gui/input audio and rendering
    """
    def __init__(self):
        log.debug('Starting Client')
        #open a window... but first set all the needed props
        wp=self.loadWindoProperites()
        #open the window
        base.openMainWindow(props = wp)
        #base.setBackgroundColor(0.06, 0.1, 0.12, 1)
        base.setBackgroundColor(0.0, 0.0, 0.0, 1)
        base.disableMouse()
        base.enableParticles()

        #needed to determine what window event fired
        self.window_focused=base.win.getProperties().getForeground()
        self.window_x=base.win.getXSize()
        self.window_y=base.win.getYSize()
        self.window_minimized=base.win.getProperties().getMinimized()

        #filter manager, post process
        self.filters=Filters()

        #audio sound effects (sfx) + music
        self.audio=Audio()
        self.audio.setMusic('background')
        self.audio.playMusic()

        #light manager
        self.lights=LightManager()

        #setup the user interface (gui+key/mouse bind)
        self.ui=UserInterface()

        #skybox
        self.sun_and_sky=Skybox(self.lights)

        #player (character) droid
        self.droid=PCDroid(self.ui)

        #some vars used later
        self.map_name=None
        self.loading_status=set()
        self.level_root=render.attachNewNode('level_root')
        self.level_root.hide()
        self.is_in_game=False

        #events
        base.win.setCloseRequestEvent('exit-event')
        self.accept('exit-event',self.onClientExit)
        self.accept( 'window-event', self.onWindowEvent)
        self.accept( 'window-reset', self.onWindowReset)
        self.accept( 'client-mouselock', self.setMouseLock)
        self.accept( 'load-level', self.onLevelLoad)
        self.accept( 'loading-done', self.onLoadingDone)
        self.accept( 'reload-shaders', self.onShaderReload)
        self.accept( 'client-set-team', self.onTeamCahnge)
        self.accept( 'client-quit', self.onQuit)
        # Task
        taskMgr.add(self.update, 'client_update')

        log.debug('Client started')

    def doSomeStuffTsk(self, task):
        x=deque(range(5000))
        for i in xrange(999):
           random.shuffle(x)
           #print i, x[0]
        #print 'done'
        return task.done

    def setMouseLock(self, lock):
        wp = WindowProperties.getDefault()
        if lock:
            wp.setMouseMode(WindowProperties.M_confined)
        else:
            wp.setMouseMode(WindowProperties.M_relative)
        if not cfg['use-os-cursor']:
            wp.setCursorHidden(True)
        base.win.requestProperties(wp)

    def loadWindoProperites(self):
        #check if we can open a fullscreen window at the requested size
        if cfg['fullscreen']:
            mods=[]
            for mode in base.pipe.getDisplayInformation().getDisplayModes():
                mods.append([mode.width, mode.height])
            if list(cfg['win-size']) not in mods:
                cfg['fullscreen']=False
                log.warning('Can not open fullscreen window at '+str(cfg['win-size']))

        #the window props should be set by this time, but make sure
        wp = WindowProperties.getDefault()
        try:
            wp.setUndecorated(cfg['undecorated'])
            wp.setFullscreen(cfg['fullscreen'])
            wp.setSize(cfg['win-size'][0],cfg['win-size'][1])
            wp.setFixedSize(cfg['win-fixed-size'])
        except:
            log.warning('Failed to set window properties, Traceback:')
            for error in traceback.format_exc().splitlines()[1:]:
                log.warning(error.strip())

        #these probably won't be in the config (?)
        wp.setOrigin(-2,-2)
        wp.setTitle('A4P')
        if not cfg['use-os-cursor']:
            wp.setCursorHidden(True)
        return wp

    def loadLevel(self, task):
        log.debug('Client loading level...')
        with open(path+'maps/'+self.map_name+'.json') as f:
            values=json.load(f)
        #set the time
        self.sun_and_sky.setTime(values['level']['time'])
        #self.sun_and_sky.show()
        #load visible objects
        for id, obj in enumerate(values['objects']):
            mesh=loader.loadModel(path+obj['model'])
            mesh.reparentTo(self.level_root)
            mesh.setPosHpr(tuple(obj['pos']), tuple(obj['hpr']))
            mesh.setTag('id_'+str(id), str(id)) #we may need to find this mesh later to link it to a Bullet object
            for name, value in obj['shader_inputs'].items():
                if isinstance(value, basestring):
                    mesh.setShaderInput(str(name), loader.loadTexture(path+value))
                if isinstance(value, float):
                    mesh.setShaderInput(str(name), value)
                if isinstance(value, list):
                    if len(value) == 2:
                        mesh.setShaderInput(str(name), Vec2(value[0], value[1]))
                    elif len(value) == 3:
                        mesh.setShaderInput(str(name), Vec3(value[0], value[1], value[2]))
                    elif len(value) == 3:
                        mesh.setShaderInput(str(name), Vec4(value[0], value[1], value[2], value[3]))
            mesh.setShader(Shader.load(Shader.SLGLSL, obj['vertex_shader'],obj['fragment_shader']))
        #set the music
        self.audio.setMusic(values['level']['music'])
        #self.level_root.prepareScene(base.win.getGsg())
        messenger.send('loading-done', ['client'])
        return task.done

    #events
    def onQuit(self):
        self.level_root.removeNode()
        self.level_root=render.attachNewNode('level_root')
        self.level_root.hide()
        if self.ui.is_zoomed:
            self.ui.zoom()
        self.sun_and_sky.hide()
        self.droid.disable()
        self.ui.unbindKeys()
        self.ui.in_game_menu.hide()
        self.ui.main_menu.show()
        self.audio.setMusic('background')
        self.loading_status=set()
        self.is_in_game=False
        messenger.send('world-clear-level')


    def onTeamCahnge(self, team):
        self.droid.setTeam(team)

    def onShaderReload(self):
        log.debug('Client: Reloading shaders')
        for mesh in self.level_root.getChildren():
            shader=mesh.getShader()
            v_shader=shader.getFilename(Shader.ST_vertex)
            f_shader=shader.getFilename(Shader.ST_fragment)
            mesh.setShader(Shader.load(Shader.SLGLSL, v_shader,f_shader))
        self.ui.main_menu.setShader(path+'shaders/gui_v.glsl', path+'shaders/gui_f.glsl')
        self.filters.reset()

    def onLoadingDone(self, target):
        log.debug(str(target)+' loading done')
        self.loading_status.add(target)
        if self.loading_status == set(['client', 'server', 'world']):
            self.ui.main_menu.hide()
            self.level_root.show()
            self.sun_and_sky.show()
            self.ui.bindKeys()
            self.droid.node.setPos(render, 20,0,2)
            self.droid.lockCamera()
            self.droid.model.show()
            self.droid.rig.show()
            self.droid.gun.show()
            self.ui.in_game_menu.showElements('hud_')
            self.ui.hideSoftCursor()
            self.ui.is_main_menu=False
            self.is_in_game=True
            messenger.send('world-link-objects', [self.droid.node, 'pc_droid_node'])

    def onLevelLoad(self, map_name):
        self.map_name=map_name
        #we wait 1.0 sec for the loading animation to finish just in case if loading takes < 1.0 sec.
        taskMgr.doMethodLater(1.0, self.loadLevel, 'client_loadLevel_task', taskChain = 'background_chain')
        #taskMgr.add(self.loadLevel, 'client_loadLevel_task', taskChain = 'background_chain')
        #the client needs to load/setup:
        # -visible geometry
        # -enviroment (skybox/dome + sunlight diection + fog + ???)
        # -water plane
        # -unmovable (point)light sources
        # -unmovable vfx
        # -the player droid

    def onClientExit(self):
        log.debug('Client exit')
        self.audio.cleanup()
        app.exit()

    def onWindowReset(self):
        wp=self.loadWindoProperites()
        base.win.requestProperties(wp)

    def onWindowMinimize(self):
        self.window_minimized=base.win.getProperties().getMinimized()
        log.debug('window-event: Minimize is '+str(self.window_minimized))

    def onWindowFocus(self):
        self.window_focused=base.win.getProperties().getForeground()
        log.debug('window-event: Focus set to '+str(self.window_focused))
        if self.is_in_game:
            self.ui.in_game_menu.showMenu(self.window_focused)
        if not self.window_focused:
            self.ui.cursor_pos=(0,0,0)
        if cfg['pause-on-focus-lost']:
            if not self.window_focused:
                self.audio.pauseMusic()
                base.win.setActive(False)
            else:
                self.audio.resumeMusic()
                base.win.setActive(True)

    def onWindowResize(self):
        self.window_x=base.win.getXSize()
        self.window_y=base.win.getYSize()
        log.debug('window-event: Resize')
        self.filters.update()
        self.ui.updateGuiNodes()

    def onWindowEvent(self,window=None):
        if window is not None: # window is none if panda3d is not started
            if self.window_x!=base.win.getXSize() or self.window_y!=base.win.getYSize():
                self.onWindowResize()
            elif window.getProperties().getMinimized() !=  self.window_minimized:
                self.onWindowMinimize()
            elif window.getProperties().getForeground() !=  self.window_focused:
                self.onWindowFocus()

    #tasks
    def update(self, task):
        dt = globalClock.getDt()
        render.setShaderInput('camera_pos', base.cam.getPos(render))
        return task.cont
Ejemplo n.º 30
0
from ui import UserInterface


uI = UserInterface()
uI.run()


Ejemplo n.º 31
0
from ui import UserInterface

if __name__ == "__main__":
    gui = UserInterface()
Ejemplo n.º 32
0
def drawScreen(SCREEN, option=None):
    ui.clearScreen()
    print(ui.Screen[SCREEN]['header'])

    if (option != None):
        print("New Password: "******"welcomeScreen")
        elif (choice == 3):
            drawScreen('findPasswordScreen')
        else:
            quit()
    elif (SCREEN == 'newPasswordScreen'):
        if (choice == 1):
            newPassword = gen.GenerateBasic()
        elif (choice == 2):
            newPassword = gen.GenerateSpecial()
        elif (choice == 3):
            newPassword = gen.GeneratePhrase()
        else:
            quit()

        drawScreen('savePasswordScreen', newPassword)

    elif (SCREEN == 'savePasswordScreen'):
        if (choice == 1):
            db.save(option)
        elif (choice == 2):
            newPassword = gen.GenerateBasic()
            drawScreen('savePasswordScreen', newPassword)
        elif (choice == 3):
            newPassword = gen.GenerateSpecial()
            drawScreen('savePasswordScreen', newPassword)
        elif (choice == 4):
            newPassword = gen.GeneratePhrase()
            drawScreen('savePasswordScreen', newPassword)
        elif (choice == 5):
            drawScreen('newPasswordScreen')
        else:
            quit()
    elif (SCREEN == 'findPasswordScreen'):
        db.searchDB(choice)
        drawScreen("welcomeScreen")
Ejemplo n.º 33
0
    return parser.parse_args()


if __name__ == '__main__':

    options, args = parse_options()

    if options.patterns_file == None:
        options.patterns_file = os.path.join(options.directory, '.dojoignore')

    try:
        print 'Monitoring files in %s' % options.directory
        print 'ignoring files in %s' % (options.patterns_file)
        print 'press ^C to quit'

        timer = Timer(options.round_time)
        ui = UserInterface(timer)
        monitor = Monitor(
            ui=ui,
            directory=options.directory,
            commands=args,
            patterns_file=options.patterns_file,
            commit=options.commit,
        )

        gtk.main()

    except KeyboardInterrupt:
        print '\nleaving...'
        sys.exit(0)