Ejemplo n.º 1
0
    def __init__(self):
        QMainWindow.__init__(self)
        self.resize(1300, 700)
        self.setFixedSize(self.size())
        self.setWindowTitle('PyChord')
        self.add_combo_boxes()
        self.add_buttons()
        self.sl = QSlider(Qt.Horizontal, self)
        self.volume = QLCDNumber(self)
        self.add_slider()

        self.actual_key = None
        self.actual_meter = 4
        self.actual_instrument = instrument.Piano()
        self.melody_stream = stream.Stream()
        self.harmonized_melody_stream = stream.Stream()
        self.reset_stream(self.melody_stream)
        self.reset_stream(self.harmonized_melody_stream)
        mixer.init(44100, -16, 2, 1024)

        self.tmpStream = stream.Stream()
        self.tmpStream.insert(instrument.Piano())
        self.lpc = lily.translate.LilypondConverter()
        self.lpc.context = lily.lilyObjects.LyMusicList()
        self.keyboard = Keyboard(self)
        self.melody = Melody(self, self.actual_key)
Ejemplo n.º 2
0
 def load_settings(self, filepath):
     self.gParams = yaml.load(open(filepath))  # load defaults
     self.gScreen = ExperimentDisplay(self.gParams)  # exp display
     self.gTimer = Timer(self.gParams)  # timers
     self.gData = DataManager(self.gParams)  # data manager
     self.gHardware = HardwareManager(self.gParams)  # data manager
     self.gDiagnostic = DiagnosticDisplay(self.gParams)  # diagnostic window
     self.gKeyboard = Keyboard(self.gParams)  # keyboard input polling
     self.gVariables = Variables(self.gParams)  # experiment variables
     self.gStates = []  # trial states
Ejemplo n.º 3
0
class Game:
    def __init__(self, frame, size):
        self.size = size
        # make a new camera based on the size of the frame, then create the frame and add a start button.
        self.camera = Camera((0, 0), self.size[0] // Unit.UNIT,
                             self.size[1] // Unit.UNIT, Unit.UNIT)
        self.player = Player(100, 100, Unit.UNIT, Unit.UNIT)
        self.keyboard = Keyboard()
        self.result = States.STATES[1]

        frame.set_keydown_handler(self.keyboard.key_down)
        frame.set_keyup_handler(self.keyboard.key_up)

        sound = Sound()
        self.tiles = Mapper.get_start_tiles(self.camera)
        sound.play_death()

    def game_draw(self, canvas):
        #########################################################################
        # IMPORTANT the tile array is a list of lists. Functionally similar, but#
        # distinct from a 2d array. To access the first element tiles[0][0] is  #
        # used. Since tiles[0] evaluates to a list object.                      #
        #########################################################################

        # for each column
        tiles_in_camera = self.camera.get_tiles_in_span(self.tiles)
        offset = Vector(self.camera.pos.x, self.camera.pos.y)
        for i in range(len(tiles_in_camera)):
            tiles_in_camera[i].draw(canvas, offset)
        self.result = self.player.draw(canvas, self.size, offset)
        canvas.draw_line((0, 0), (0, self.size[1]), 40, "#000000")
        canvas.draw_line((self.size[0], 0), (self.size[0], self.size[1]), 40,
                         "#000000")
        self.player.draw_lives(canvas)
        self.tick(tiles_in_camera)

        if self.result is not States.STATES[1]:
            self.game_over()

        return self.result

    def tick(self, sprites_to_tick):
        self.keyboard.tick(self.player, self.camera)
        self.camera.tick()
        for s in sprites_to_tick:
            s.tick()
        self.player.tick()

    def game_over(self):
        # TODO: add the game over transition and everything
        self.player = None
        self.camera = None
        self.keyboard = None
        self.tiles = None
Ejemplo n.º 4
0
    def __init__(self, frame, size):
        self.size = size
        # make a new camera based on the size of the frame, then create the frame and add a start button.
        self.camera = Camera((0, 0), self.size[0] // Unit.UNIT,
                             self.size[1] // Unit.UNIT, Unit.UNIT)
        self.player = Player(100, 100, Unit.UNIT, Unit.UNIT)
        self.keyboard = Keyboard()
        self.result = States.STATES[1]

        frame.set_keydown_handler(self.keyboard.key_down)
        frame.set_keyup_handler(self.keyboard.key_up)

        sound = Sound()
        self.tiles = Mapper.get_start_tiles(self.camera)
        sound.play_death()
Ejemplo n.º 5
0
 def build(self):
     self.game = Game()
     self.keyboard = Keyboard()
     self.mouse = Mouse()
     self.settings = Settings()
     # Create loop with 1/60 sec delay
     Clock.schedule_interval(self.update, 1.0 / 60.0)
     return self.game
Ejemplo n.º 6
0
    def __init__(self, controller, parent=None):
        super(MindType, self).__init__(parent)

        # variables used for pausing
        self.controller = controller
        self.interval = 100

        # Creating main panel which contains everything
        self.main_panel = QtGui.QVBoxLayout()
        self.main_panel.setContentsMargins(0, 0, 0, 0)

        # creating header panel which has start, pause/resume and text display
        self.header_panel = QtGui.QHBoxLayout()
        self.main_panel.addLayout(self.header_panel)

        # creating header panel buttons
        self.character_display_panel = QtGui.QLabel("Enter Text!")
        self.start_button = QtGui.QPushButton("Start")
        self.end_button = QtGui.QPushButton("Pause")

        # setting button click listeners
        self.start_button.clicked.connect(self.start())
        self.end_button.clicked.connect(self.pause_resume())

        # adding buttons to header panel
        self.header_panel.addWidget(self.character_display_panel)
        self.header_panel.addWidget(self.start_button)
        self.header_panel.addWidget(self.end_button)

        # adding keyboard gui to main panel
        # creating a button grid
        self.grid = QtGui.QGridLayout()
        self.grid.setSpacing(0)
        self.keyboard = Keyboard(self.main_panel, self.character_display_panel,
                                 self.interval)

        # setting layout to main_panel
        self.setLayout(self.main_panel)
Ejemplo n.º 7
0
	def __init__(self, app, done=1, skin=None):
		self.app = app
		self.playlistdir = self.app.opts['playlistdir']
		print "Playlistdir = %s" % self.playlistdir
		self.sdb = app.sdb
		self.plmDone = done
		self.kbd = Keyboard(app, done=KBD_DONE, cancel=KBD_CANCEL, skin=skin)
		self.playlists = []
		self.loadPlaylists()
		#self.buildPLMenu()
		self.menu = []
		self.active = False
		self.plIndex = None
		self.clearPending = False
		self.chosenPlaylist = None
		self.albumToAdd = None
		self.artistToAdd = None
		self.songToAdd = None
		self.normalMessage = ""
		self.ple = PLEdit(app)
Ejemplo n.º 8
0
class MyWindow(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)
        self.resize(1300, 700)
        self.setFixedSize(self.size())
        self.setWindowTitle('PyChord')
        self.add_combo_boxes()
        self.add_buttons()
        self.sl = QSlider(Qt.Horizontal, self)
        self.volume = QLCDNumber(self)
        self.add_slider()

        self.actual_key = None
        self.actual_meter = 4
        self.actual_instrument = instrument.Piano()
        self.melody_stream = stream.Stream()
        self.harmonized_melody_stream = stream.Stream()
        self.reset_stream(self.melody_stream)
        self.reset_stream(self.harmonized_melody_stream)
        mixer.init(44100, -16, 2, 1024)

        self.tmpStream = stream.Stream()
        self.tmpStream.insert(instrument.Piano())
        self.lpc = lily.translate.LilypondConverter()
        self.lpc.context = lily.lilyObjects.LyMusicList()
        self.keyboard = Keyboard(self)
        self.melody = Melody(self, self.actual_key)

    def change_volume(self, vl):
        mixer.music.set_volume(vl / 100.0)
        self.volume.display(vl)

    def add_buttons(self):
        play_button = QPushButton('Play', self)
        play_button.move(1100, 300)
        play_button.clicked.connect(self.play_notes)

        reset_button = QPushButton('Reset', self)
        reset_button.move(1100, 350)
        reset_button.clicked.connect(self.reset)

        notes_button = QPushButton('Show Notes', self)
        notes_button.clicked.connect(self.show_notes)
        notes_button.move(1100, 400)

        save_button = QPushButton('Save', self)
        save_button.clicked.connect(self.save)
        save_button.move(1100, 450)

    def add_combo_boxes(self):
        key_info = QLabel('Choose a key:', self)
        key_info.move(600, 50)
        key_choice = QComboBox(self)
        key_choice.move(600, 100)
        key_choice.addItems(['None', 'C', 'D', 'E', 'F', 'G', 'A', 'B'])
        key_choice.currentIndexChanged.connect(self.change_key)

        meter_info = QLabel('Choose a meter:', self)
        meter_info.move(400, 50)
        meter_choice = QComboBox(self)
        meter_choice.move(400, 100)
        meter_choice.addItems(['4/4', '3/4', '2/4'])
        meter_choice.currentIndexChanged.connect(self.change_meter)

        instrument_choice = QComboBox(self)
        instrument_choice.move(1100, 250)
        instrument_choice.addItems(
            ['Piano(default)', 'Guitar', 'Violin', 'Flute', 'Mandolin'])
        instrument_choice.currentIndexChanged.connect(self.change_instrument)

    def add_slider(self):
        self.sl.setMinimum(0)
        self.sl.setMaximum(100)
        self.sl.setValue(80)
        self.sl.setTickInterval(1)
        self.sl.move(1100, 220)
        self.sl.valueChanged.connect(
            lambda: self.change_volume(self.sl.value()))

        self.volume.move(1100, 180)
        self.volume.display(80)

    def play_notes(self):
        try:
            if not self.melody.is_well_rhythmic:
                confirm = QMessageBox()
                confirm.setWindowTitle('Error')
                confirm.setText('The rhythm is not correct.')
                confirm.setIcon(QMessageBox.Information)
                confirm.exec()
            else:
                if self.actual_key is not None:
                    self.melody.harmonize()
                    mixer.music.load(
                        self.harmonized_melody_stream.write('midi'))
                    mixer.music.play()
                else:
                    mixer.music.load(self.melody_stream.write('midi'))
                    mixer.music.play()
        except exceptions21.StreamException:
            pass

    def show_notes(self):
        if not self.melody.is_well_rhythmic:
            confirm = QMessageBox()
            confirm.setWindowTitle('Error')
            confirm.setText('The rhythm is not correct.')
            confirm.setIcon(QMessageBox.Information)
            confirm.exec()
        else:
            self.lpc.context.contents = []
            self.lpc.appendObjectsToContextFromStream(self.melody_stream)

            with open('notes.ly', 'w+') as f:
                f.write('\\version "2.20.0"\n')
                if self.actual_key is None:
                    f.write("{\n")
                    f.write('\\key c \\major \n')
                    f.write(str(self.lpc.context))
                    f.write("}\n")
                else:
                    f.write('{<<\n')
                    f.write('\\chords {')
                    for i in self.melody.list_of_chords:
                        f.write(i.lower() + " ")
                    f.write('}\n')
                    f.write('{\\key ' + self.actual_key.tonic.name.lower() +
                            ' \\' + self.actual_key.mode)
                    f.write('\n')
                    f.write(str(self.lpc.context))
                    f.write('}>>}\n')

            if platform.system() == 'Linux':
                process = subprocess.Popen(['lilypond notes.ly'], shell=True)
                process.wait(100)

                subprocess.Popen(['chmod 755 notes.pdf'], shell=True)
                subprocess.Popen(['xdg-open notes.pdf'], shell=True)

            elif platform.system() == 'Windows':
                process = subprocess.Popen(['powershell', 'lilypond notes.ly'])
                process.wait(100)

                subprocess.Popen(['powershell', '.\\notes.pdf'])

    def save(self):
        if not self.melody.is_well_rhythmic:
            confirm = QMessageBox()
            confirm.setWindowTitle('Error')
            confirm.setText('The rhythm is not correct.')
            confirm.setIcon(QMessageBox.Information)
            confirm.exec()
        else:
            if not os.path.exists('music'):
                os.makedirs('music')
            today = date.today()
            flag = True
            count = 1
            path = ''

            while flag is True:
                path = os.path.join('music',
                                    '{}.{}.mid'.format(str(count), str(today)))
                flag = os.path.isfile(path)
                count += 1

            self.harmonized_melody_stream.write('midi', fp=path)
            confirm = QMessageBox()
            confirm.setWindowTitle('Confirmation')
            confirm.setText('File saved')
            confirm.setIcon(QMessageBox.Information)
            confirm.exec()

    def add_note(self, my_note):
        self.melody.rhythmic_values_sum = sum(
            self.melody.note_buttons[i].rhythmic_value
            for i in range(len(self.melody.note_buttons)))
        if self.melody.rhythmic_values_sum < self.melody.max_notes:
            self.melody_stream.insert(self.melody.rhythmic_values_sum + 2,
                                      note.Note(my_note.nameWithOctave))
            for i in range(8):
                if mixer.Channel(i).get_busy():
                    pass
                else:
                    if platform.system() == 'Linux':
                        mixer.Channel(i).play(
                            mixer.Sound('notes/{}.wav'.format(my_note)))
                    elif platform.system() == 'Windows':
                        mixer.Channel(i).play(
                            mixer.Sound('notes\\{}.wav'.format(my_note)))
                    break
            self.melody.add_note_to_melody(my_note)
            self.melody.show_melody()

    def reset_stream(self, stream_to_reset):
        stream_to_reset.clear()
        stream_to_reset.insert(0, self.actual_instrument)
        stream_to_reset.insert(
            1, meter.TimeSignature('{}/4'.format(self.actual_meter)))

    def change_instrument(self, choice):
        instruments = [
            instrument.Piano(),
            instrument.AcousticGuitar(),
            instrument.Violin(),
            instrument.Flute(),
            instrument.Mandolin()
        ]
        self.actual_instrument = instruments[choice]
        self.melody_stream[0] = self.actual_instrument

    def reset(self):
        for button in self.melody.note_buttons:
            button.hide()
        self.melody.note_buttons.clear()
        self.melody.notes_counter = 0
        self.melody.rhythmic_values_sum = 0
        self.reset_stream(self.melody_stream)
        self.reset_stream(self.harmonized_melody_stream)

    def change_key(self, choice):
        self.reset()
        self.keyboard.reset()
        if choice == 0:
            self.actual_key = None
        else:
            keys = ['None', 'C', 'D', 'E', 'F', 'G', 'A', 'B']
            self.actual_key = key.Key(keys[choice])
            self.keyboard.on_key_change(self.actual_key)

        self.melody.actual_key = self.actual_key

    def change_meter(self, choice):
        self.reset()
        meters = [4, 3, 2]
        self.actual_meter = meters[choice]
        self.melody.on_meter_change(self.actual_meter)
        self.update(0, 0, 1000, 1000)

    def paintEvent(self, e):
        lines = QPainter(self)
        lines.setPen(QPen(QColor(240, 240, 240), 10, Qt.SolidLine))
        for i in range(17):
            lines.drawLine(250 + i * 45, 290, 250 + i * 45, 350)

        lines.setPen(QPen(Qt.black, 10, Qt.SolidLine))
        for i in range(5):
            lines.drawLine(250 + i * self.actual_meter * 45, 290,
                           250 + i * self.actual_meter * 45, 350)
        lines.end()
Ejemplo n.º 9
0
Archivo: asp.py Proyecto: ljonesfl/asp
from Screen import Screen
from Keyboard import Keyboard
from Game import Game

screen = Screen()
window = screen.create_window()

game = Game(window, Keyboard(window))

game.play()
Ejemplo n.º 10
0
 def keyPress(self, key, x, y):
     Keyboard.keydown(self.Keyboard, key, x, y)
     self.display()
Ejemplo n.º 11
0
    def enlisting(self, sender_id, pipeline, states):
        for messaging_text, assert_state in zip(pipeline, states):
            current_state = STATES[sender_id]
            entity, value = wit_response(messaging_text)

            self.assertEqual(current_state, assert_state)
            if current_state == 'wait_parent_confirm_again':
                if value == 'positive':
                    if check_for_existance():
                        send_message(
                            sender_id,
                            Keyboard(
                                text="Ура! У вас уже есть аккаунт :)"
                                "Если вы забыли пароль, можно установить новый по ссылке {{password_reset_link}}"
                                "Чтобы включить программу чтения с экрана, нажмите Ctrl+Alt+Z. Для просмотра списка быстрых клавиш нажмите Ctrl+косая черта.",
                                titles=None))
                    else:
                        send_message(
                            sender_id,
                            Keyboard(
                                text="💫 Done! Я создал вам аккаунт в Skyeng. "
                                "Логин: {{customer.email}}, пароль от личного кабинета придет вам на почту.",
                                titles=None))
                        days = get_days()
                        send_message(
                            sender_id,
                            Keyboard(
                                text=
                                "Выберите день, на который хотите записаться 🗓️",
                                titles=days))
                        STATES[sender_id] = "wait_days"
                elif value == 'negative':
                    STATES[sender_id] = "initial"
                    ENLISTING.remove(sender_id)
                    send_message(
                        sender_id,
                        Keyboard(titles=None,
                                 text="Будем ждать вашего возвращения 🤗"))

            elif current_state == "wait_parent_confirm":
                if value == 'positive':
                    # TODO refactor this routine
                    if check_for_existance():
                        send_message(
                            sender_id,
                            Keyboard(
                                text="Ура! У вас уже есть аккаунт :)"
                                "Если вы забыли пароль, можно установить новый по ссылке {{password_reset_link}}"
                                "Чтобы включить программу чтения с экрана, нажмите Ctrl+Alt+Z. Для просмотра списка быстрых клавиш нажмите Ctrl+косая черта.",
                                titles=None))
                    else:
                        send_message(
                            sender_id,
                            Keyboard(
                                text="💫 Done! Я создал вам аккаунт в Skyeng. "
                                "Логин: {{customer.email}}, пароль от личного кабинета придет вам на почту.",
                                titles=None))
                        days = get_days()
                        send_message(
                            sender_id,
                            Keyboard(
                                text=
                                "Выберите день, на который хотите записаться 🗓️",
                                titles=days))
                        STATES[sender_id] = "wait_days"
                elif value == 'negative':
                    STATES[sender_id] = "wait_parent_confirm_again"
                    send_message(
                        sender_id,
                        Keyboard(
                            text=
                            "К сожалению, мы не можем записать ребенка на урок,"
                            "если его родитель не сможет присутствовать на занятии 😞",
                            titles=[
                                "Подтверждаю присутствие родителя",
                                "Ну, что ж, жаль"
                            ]))

            elif current_state == "wait_kid_age":
                STATES[sender_id] = "wait_parent_confirm"
                send_message(
                    sender_id,
                    Keyboard(
                        text=
                        "Пожалуйста, подтвердите присутствие родителя на уроке."
                        "Это обязательное условие, когда ученик младше 18 лет",
                        titles=["Подтверждаю", "Не подтверждаю"]))
            elif current_state == "wait_time":
                write_time()
                send_message(
                    sender_id,
                    Keyboard(
                        text=
                        "🎉 Вы записаны. ВУ пройдет {{intro_lesson_date}} в {{intro_lesson_time}}. До встречи!"
                        "Если передумаете, отменить или изменить запись можно в личном кабинете.",
                        titles=None))
                send_message(
                    sender_id,
                    Keyboard(text="Добавить в календарь?",
                             titles=["Да", "Нет"]))
                STATES[sender_id] = 'calendar_wait'

            elif current_state == "wait_days":
                write_day(messaging_text)
                send_message(
                    sender_id,
                    Keyboard(text="👍Great! А теперь выберите удобное время",
                             titles=get_time()))
                STATES[sender_id] = "wait_time"

            elif current_state == 'enlisting_start':
                send_message(
                    sender_id,
                    Keyboard(
                        text=
                        "Привет 👋 Я запишу вас на бесплатный урок в онлайн-школу английского языка Skyeng."
                        "Давайте проверим, есть ли у вас аккаунт. Он нужен для регистрации на занятие и для доступа на платформу, где будет проходить урок. Если аккаунта нет — я его создам."
                        "Пожалуйста, введите ваш email.",
                        titles=None))
                STATES[sender_id] = 'wait_email'
            elif current_state == 'wait_email':
                save_user_email()
                send_message(
                    sender_id,
                    Keyboard(text="Отлично! Теперь укажите возраст ученика",
                             titles=["До 18", "18+"]))
                STATES[sender_id] = 'wait_age'
            elif current_state == 'wait_age':
                if value == 'positive':
                    if check_for_existance():
                        send_message(
                            sender_id,
                            Keyboard(
                                text="Ура! У вас уже есть аккаунт :)"
                                "Если вы забыли пароль, можно установить новый по ссылке {{password_reset_link}}"
                                "Чтобы включить программу чтения с экрана, нажмите Ctrl+Alt+Z. Для просмотра списка быстрых клавиш нажмите Ctrl+косая черта.",
                                titles=None))
                    else:
                        send_message(
                            sender_id,
                            Keyboard(
                                text="💫 Done! Я создал вам аккаунт в Skyeng. "
                                "Логин: {{customer.email}}, пароль от личного кабинета придет вам на почту.",
                                titles=None))
                        days = get_days()
                        send_message(
                            sender_id,
                            Keyboard(
                                text=
                                "Выберите день, на который хотите записаться 🗓️",
                                titles=days))
                        STATES[sender_id] = "wait_days"
                else:
                    send_message(
                        sender_id,
                        Keyboard(text="Уточните категорию",
                                 titles=["До 11 лет", "12+"]))
                    STATES[sender_id] = 'wait_kid_age'
Ejemplo n.º 12
0
    def webhook(self, pipeline, states_line):
        # log(data)

        sender_id = 13

        for (messaging_text, assert_state) in zip(pipeline, states_line):
            if sender_id in ENLISTING:
                self.enlisting(sender_id, messaging_text)
            entity, value = wit_response(messaging_text)
            current_state = STATES.get(sender_id, 'initial')
            # self.assertEquals(current_state, assert_state)
            if current_state == "info_wait":
                if value == "somethingelse":
                    # TODO optimize this button
                    send_message(
                        sender_id,
                        Keyboard(
                            text=
                            "Skyeng Magazine — онлайн-журнал о том, как перестать бояться английского, узнать его получше и полюбить. Читать: https://magazine.skyeng.ru/"
                            "YouTube-канал — нескучный английский с Таней Стариковой и американцем Дэниелом. Смотреть: https://www.youtube.com/user/skyengschool"
                            "Бесплатное приложение Skyeng — учите новые слова. Единый словарь для ваших уроков, тематических наборов, фильмов и песен. Установить: {{app_download_link}}"
                            "Расширение для браузера — добавляйте в приложение Skyeng слова с сайтов при помощи расширения для браузера. Установить: {{extension_download_link}}"
                            "'Полезные' письма — бесплатные email-курсы про английский язык. Выбрать: https://school.skyeng.ru/mailing"
                            "Вебинары — бесплатные тематические онлайн-лекции. Афиша: http://webinar.skyeng.ru/afisha"
                        ))
                    app.logger.info("something else")
                    STATES[sender] = "continue"
                    send_message(
                        sender_id,
                        Keyboard(titles=["Да", "Нет"], text="Продолжим?"))
                elif value == "feedback":
                    send_message(
                        sender_id,
                        Keyboard(text="Skyeng - топ! Отвечаю", titles=[]))
                    STATES[sender_id] = "continue"
                    app.logger.info("FEEDBACKS!!")
                    send_message(
                        sender_id,
                        Keyboard(titles=["Да", "Нет"], text="Продолжим?"))
                elif value == "numbers":
                    STATES[sender_id] = "continue"
                    send_message(
                        sender_id,
                        Keyboard(
                            titles=None,
                            text=
                            "Skyeng — это онлайн-школа английского языка нового поколения. В школе работают профессионалы, помогающие жителям современных мегаполисов выучить английский язык в условиях недостатка времени."
                            "\n5460 преподавателей\n58700 учеников\n4218000 уроков проведено с момента основания\n"
                            "50 минут — продолжительность урока\n24 часа в сутки — идут занятия в школе\n1-й урок — бесплатно\nпреподавателем Skyeng становится только 1 из 36 кандидатов"
                        ))
                    send_message(
                        sender_id,
                        Keyboard(titles=["Да", "Нет"], text="Продолжим?"))
                elif value == "how":
                    STATES[sender_id] = "continue"
                    send_message(
                        sender_id,
                        Keyboard(
                            titles=None,
                            text=
                            "Как проходят уроки в Skyeng — https://magazine.skyeng.ru/vimbox/\n"
                            "Про приложение Skyeng — https://magazine.skyeng.ru/skyeng-app/"
                        ))
                    send_message(
                        sender_id,
                        Keyboard(titles=["Да", "Нет"], text="Продолжим?"))
            elif current_state == "thank_you_wait":
                # TODO enlisting routine
                if value == 'negative':
                    send_message(sender_id,
                                 Keyboard(titles=None, text="Пока!!!"))
                    STATES[sender_id] = 'initial'
                elif value == 'positive':

                    STATES[sender_id] = 'enlisting_start'
                    ENLISTING.add(sender_id)
                    self.enlisting(sender_id, messaging_text)
            elif current_state == "continue":
                if value == 'negative':
                    send_message(
                        sender_id,
                        Keyboard(
                            text="Приятно было пообщаться 🤗\n"
                            "Хотите записаться на бесплатный урок английского?\n"
                            "Занятие длится 50 минут и проходит онлайн. На нем:\n"
                            "✔️Сформулируем ваши цели\n"
                            "✔️Определим уровень английского\n"
                            "✔️Расскажем про учебную платформу\n",
                            titles=['Да', "Нет"]))
                    STATES[sender_id] = "thank_you_wait"
                elif value == 'positive':
                    send_message(
                        sender_id,
                        Keyboard(
                            text="Что вам было бы интересно узнать?",
                            titles=[
                                "Skyeng в цифрах",
                                "Отзывы студентов",
                                # "Что есть кроме английского?", TODO optimize
                                "Как это работает?"
                            ]))
                    STATES[sender_id] = "info_wait"
            elif current_state == 'initial_wait':
                if value == 'positive' or value == 'neutral':
                    send_message(
                        sender_id,
                        Keyboard(
                            text="Что вам было бы интересно узнать?",
                            titles=[
                                "Skyeng в цифрах",
                                "Отзывы студентов",
                                # "Что есть кроме английского?", TODO optimize
                                "Как это работает?"
                            ]))
                    STATES[sender_id] = "info_wait"
                if value == 'negative':
                    send_message(
                        sender_id,
                        Keyboard(text="Окей 🤐", titles=["Передумали?"]))
                if value == 'once_again':
                    STATES['sender_id'] = 'initial_wait'
                    send_message(
                        sender_id,
                        Keyboard(
                            titles=['Да', 'Нет', 'Не знаю'],
                            text='Привет 👋 Рассказать вам немного о Skyeng?'))
            elif value == "greeting" or current_state == 'initial':
                send_message(
                    sender_id,
                    Keyboard(titles=['Да', 'Нет', 'Не знаю'],
                             text='Привет 👋 Рассказать вам немного о Skyeng?'))
                STATES[sender_id] = 'initial_wait'
Ejemplo n.º 13
0
        # print("assigning in_game: " + str(in_game))

    # loops through all the states:
    if current_state is States.STATES[0]:
        # print("In " + str(States.STATES[0]) + " condition")
        current_state = WelcomePage.welcome_page_draw(frame, canvas, SIZE)
        print("current_state after button press: " + str(current_state))

    elif current_state is States.STATES[1]:

        # Creates a new game instance if there isn't one yet
        if not in_game:
            game = Game(frame, SIZE)
            in_game = True

        current_state = game.game_draw(canvas)


current_state = States.STATES[0]
UNIT = Unit.UNIT
ui = UI()
in_game = False
# define the size in terms of units
SIZE = (UNIT * 10, UNIT * 8)
keyboard = Keyboard()
frame = simplegui.create_frame("Frame", SIZE[0], SIZE[1])
frame.set_keydown_handler(keyboard.key_down)
frame.set_keyup_handler(keyboard.key_up)
frame.set_draw_handler(draw)
frame.start()
Ejemplo n.º 14
0
class Experiment:
    __metaclass__ = abc.ABCMeta

    # constructor
    def __init__(self):
        self.pythonver = sys.version_info[:2]
        if self.pythonver < (3, 5):
            print("Please run with python version 3.6 or higher")
            sys.exit(0)
        else:
            print("Current python version is " + str(self.pythonver))

    # initialize experiment with defaults provided in yaml file
    def load_settings(self, filepath):
        self.gParams = yaml.load(open(filepath))  # load defaults
        self.gScreen = ExperimentDisplay(self.gParams)  # exp display
        self.gTimer = Timer(self.gParams)  # timers
        self.gData = DataManager(self.gParams)  # data manager
        self.gHardware = HardwareManager(self.gParams)  # data manager
        self.gDiagnostic = DiagnosticDisplay(self.gParams)  # diagnostic window
        self.gKeyboard = Keyboard(self.gParams)  # keyboard input polling
        self.gVariables = Variables(self.gParams)  # experiment variables
        self.gStates = []  # trial states

    # initialize data manager and provide format to expect data in
    def set_data_format(self, dataformat):
        self.gData.init_data_manager(dataformat)

    # set directory in which data is stored
    def set_data_directory(self, data_dir):
        self.gData.set_data_directory(data_dir)

    # attached hardware object with given name
    def add_hardware(self, hardware_name, hardware_obj):
        self.gHardware[hardware_name] = hardware_obj

    # set subject id (used by data manager as file name to save data to disk)
    def set_subject_id(self, subject_id):
        self.gData.set_subject_id(subject_id)

    # set states used to progress through a trial
    def set_trial_states(self, *sequential, **named):
        enums = dict(zip(sequential, range(len(sequential))), **named)
        self.gStates = type('Enum', (), enums)

    # get subject id
    def get_subject_id(self):
        return self.gData.subject_id

    # get run number
    def get_runno(self):
        return self.gData.run

    # toggle diagnostic window
    def diagnostic(self, mode):
        self.gDiagnostic.diagnostic(mode, self.gParams)

    # start run in experiment
    def start_run(self):
        # posting run starting message
        self.gData.add_dbg_event('starting run ' + str(self.get_runno()))

        # reset all timers at the start of the run
        self.gTimer.reset_all()

        # loop over all trials in the target file
        for i in range(self.gTrial.getTrialNum()):
            # run abstract function for each trial
            self.state = 0

            while self.state != self.gStates.END_TRIAL:
                self.trial()
                self.flip()

            # call onTrialEnd function to add data records for trial
            # save trial data to file
            # go to next trial
            self.onTrialEnd()
            self.gData.write_data()
            self.gTrial.nextTrial()

        # posting run ending message
        # save debug and raw data
        self.gData.add_dbg_event('run successfully completed')
        self.gData.write_dbg_data()

    # flip screen buffers
    def flip(self):
        if self.gScreen.handle != []:
            self.updateScreen()
            self.gScreen.handle.flip()

        if self.gDiagnostic.handle != []:
            self.updateDiagnostic()
            self.gDiagnostic.handle.flip()

    # close all screens associated with experiment
    def close_screens(self):
        self.gScreen.close()
        self.gDiagnostic.close()

    # control block
    def control(self):
        while True:
            resp = self.gKeyboard.poll(self.get_subject_id())

            if resp is None:
                continue

            elif resp[0] == 'quit':
                self.exit()
                break

            elif resp[0] == 'run':
                self.gData.run = resp[1]
                self.gTrial = TargetFile(resp[2])
                self.start_run()

            elif resp[0] == 'subj':
                self.set_subject_id(resp[1])

            else:
                self.define_command(resp[0])

    # define user commands
    def define_command(self, cmd):
        print('unrecognized command')

    # close all windows and clear memory
    def exit(self):
        self.close_screens()
        del self.gTimer
        del self.gData
        del self.gScreen
        del self.gDiagnostic
        del self.gKeyboard
        del self.gParams
        del self.gHardware

    # main experiment loop for each trial
    # provided as an abstract function to be overloaded by inheriting class
    @abc.abstractmethod
    def trial(self):
        """Main experiment trial loop provided by the base class"""

    # main drawing function to be called prior to screen refresh
    # provided as an abstract function to be overloaded by inheriting class
    @abc.abstractmethod
    def updateScreen(self):
        """main drawing function to be called prior to screen refresh"""

    # main updating function to be called prior to diagnostic info refresh
    # provided as an abstract function to be overloaded by inheriting class
    def updateDiagnostic(self):
        """main drawing function to be called prior to diagnostic info refresh"""

    # function is called when trial ends, can be used to save data
    # provided as an abstract function to be overloaded by inheriting class
    @abc.abstractmethod
    def onTrialEnd(self):
        """main function to be called when trial ends"""
Ejemplo n.º 15
0
    def __init__(self, master, valves):
        Frame.__init__(self, master, bg='sky blue', width=1366, height=768)
        self.master = master

        self.canvas = Canvas(self, height=640, width=1300, bg='sky blue')
        self.frame = Frame(self.canvas, bg='sky blue')
        self.frame.bind('<Button-1>', self.process_click_out)

        self.scrollbar = Scrollbar(self,
                                   orient='vertical',
                                   command=self.canvas.yview)
        self.scrollbar.configure(activebackground='DarkRed',
                                 background='red',
                                 width=40)
        self.canvas.configure(yscrollcommand=self.scrollbar.set,
                              scrollregion=[0, 0, 1366, 2100])

        self.scrollbar.pack(side='right', fill='y')
        self.canvas.pack(side='left')
        self.canvas.create_window((0, 0), window=self.frame, anchor='nw')

        self.keyboard = Keyboard(self.master)

        self.valves = valves
        self.frame.config(bg='sky blue')

        index = 0
        while index < 25:
            self.frame.grid_rowconfigure(index, minsize=80)
            self.frame.grid_columnconfigure(index, minsize=150)
            index += 1

        num_label = [
            Label(self.frame, text='1'),
            Label(self.frame, text='2'),
            Label(self.frame, text='3'),
            Label(self.frame, text='4'),
            Label(self.frame, text='5'),
            Label(self.frame, text='6'),
            Label(self.frame, text='7'),
            Label(self.frame, text='8'),
        ]
        row = 1
        for each in num_label:
            each.grid(row=row, column=0)
            each.config(width=3,
                        font=('Lucida Console', 30),
                        bg='sky blue',
                        fg='RoyalBlue4')
            row += 3

        text_label = [
            Label(self.frame, text='VALVE 1:  '),
            Label(self.frame, text='ACTION A: '),
            Label(self.frame, text='ACTION B: '),
            Label(self.frame, text='VALVE 2:  '),
            Label(self.frame, text='ACTION A: '),
            Label(self.frame, text='ACTION B: '),
            Label(self.frame, text='VALVE 3:  '),
            Label(self.frame, text='ACTION A: '),
            Label(self.frame, text='ACTION B: '),
            Label(self.frame, text='VALVE 4:  '),
            Label(self.frame, text='ACTION A: '),
            Label(self.frame, text='ACTION B: '),
            Label(self.frame, text='VALVE 5:  '),
            Label(self.frame, text='ACTION A: '),
            Label(self.frame, text='ACTION B: '),
            Label(self.frame, text='VALVE 6:  '),
            Label(self.frame, text='ACTION A: '),
            Label(self.frame, text='ACTION B: '),
            Label(self.frame, text='VALVE 7:  '),
            Label(self.frame, text='ACTION A: '),
            Label(self.frame, text='ACTION B: '),
            Label(self.frame, text='VALVE 8:  '),
            Label(self.frame, text='ACTION A: '),
            Label(self.frame, text='ACTION B: ')
        ]
        row = 1
        for each in text_label:
            each.grid(row=row, column=1)
            each.config(width=12,
                        font=('Lucida Console', 30),
                        bg='sky blue',
                        fg='RoyalBlue4')
            row += 1

        self.valve_label = [
            Label(self.frame, textvariable=self.valves[0].get_name()),
            Label(self.frame, textvariable=self.valves[1].get_name()),
            Label(self.frame, textvariable=self.valves[2].get_name()),
            Label(self.frame, textvariable=self.valves[3].get_name()),
            Label(self.frame, textvariable=self.valves[4].get_name()),
            Label(self.frame, textvariable=self.valves[5].get_name()),
            Label(self.frame, textvariable=self.valves[6].get_name()),
            Label(self.frame, textvariable=self.valves[7].get_name())
        ]
        row = 1
        for each in self.valve_label:
            each.grid(row=row, column=2)
            each.config(width=12,
                        font=('Lucida Console', 30),
                        bg='sky blue',
                        fg='RoyalBlue4',
                        anchor='w')
            each.bind('<Button-1>', self.process_click_out)
            row += 3

        self.entry_field = [
            Entry(self.frame, text=''),
            Entry(self.frame, text=''),
            Entry(self.frame, text=''),
            Entry(self.frame, text=''),
            Entry(self.frame, text=''),
            Entry(self.frame, text=''),
            Entry(self.frame, text=''),
            Entry(self.frame, text=''),
            Entry(self.frame, text=''),
            Entry(self.frame, text=''),
            Entry(self.frame, text=''),
            Entry(self.frame, text=''),
            Entry(self.frame, text=''),
            Entry(self.frame, text=''),
            Entry(self.frame, text=''),
            Entry(self.frame, text=''),
            Entry(self.frame, text=''),
            Entry(self.frame, text=''),
            Entry(self.frame, text=''),
            Entry(self.frame, text=''),
            Entry(self.frame, text=''),
            Entry(self.frame, text=''),
            Entry(self.frame, text=''),
            Entry(self.frame, text='')
        ]
        row = 1
        for each in self.entry_field:
            each.grid(row=row, column=3)
            each.config(width=12,
                        font=('Lucida Console', 30),
                        bg='sky blue',
                        fg='RoyalBlue4')
            each.bind('<Button-1>', self.process_click_in)
            row += 1

        self.action_a_label = [
            Label(self.frame, textvariable=self.valves[0].get_action_a()),
            Label(self.frame, textvariable=self.valves[1].get_action_a()),
            Label(self.frame, textvariable=self.valves[2].get_action_a()),
            Label(self.frame, textvariable=self.valves[3].get_action_a()),
            Label(self.frame, textvariable=self.valves[4].get_action_a()),
            Label(self.frame, textvariable=self.valves[5].get_action_a()),
            Label(self.frame, textvariable=self.valves[6].get_action_a()),
            Label(self.frame, textvariable=self.valves[7].get_action_a())
        ]
        row = 2
        for each in self.action_a_label:
            each.grid(row=row, column=2)
            each.config(width=12,
                        font=('Lucida Console', 30),
                        bg='sky blue',
                        fg='RoyalBlue4',
                        anchor='w')
            each.bind('<Button-1>', self.process_click_out)
            row += 3

        self.action_b_label = [
            Label(self.frame, textvariable=self.valves[0].get_action_b()),
            Label(self.frame, textvariable=self.valves[1].get_action_b()),
            Label(self.frame, textvariable=self.valves[2].get_action_b()),
            Label(self.frame, textvariable=self.valves[3].get_action_b()),
            Label(self.frame, textvariable=self.valves[4].get_action_b()),
            Label(self.frame, textvariable=self.valves[5].get_action_b()),
            Label(self.frame, textvariable=self.valves[6].get_action_b()),
            Label(self.frame, textvariable=self.valves[7].get_action_b())
        ]

        row = 3
        for each in self.action_b_label:
            each.grid(row=row, column=2)
            each.config(width=12,
                        font=('Lucida Console', 30),
                        bg='sky blue',
                        fg='RoyalBlue4',
                        anchor='w')
            each.bind('<Button-1>', self.process_click_out)
            row += 3

        self.lock()
Ejemplo n.º 16
0
from pynput import keyboard

MAX_POTS_X = 1457
MAX_POTS_Y = 777

AMOUNT_POTS_X = 1441
AMOUNT_POTS_Y = 878

BUY_POTS_X = 1353
BUY_POTS_Y = 1033

flag = True

mouse = Mouse()
keys = Keyboard()


def detectMAXButton():
    while True:
        cmd1 = input(
            "detect your cursor position after 3 secs later, please move your cursor to MAX button and wait for count down, type 'y' to continue.\n"
        )
        if cmd1.__eq__("y"):
            break

    while True:
        countdown(3)
        x, y = mouse.get_position()
        global MAX_POTS_X, MAX_POTS_Y
        MAX_POTS_X = x
Ejemplo n.º 17
0
class MindType(QtGui.QDialog):
    def __init__(self, controller, parent=None):
        super(MindType, self).__init__(parent)

        # variables used for pausing
        self.controller = controller
        self.interval = 100

        # Creating main panel which contains everything
        self.main_panel = QtGui.QVBoxLayout()
        self.main_panel.setContentsMargins(0, 0, 0, 0)

        # creating header panel which has start, pause/resume and text display
        self.header_panel = QtGui.QHBoxLayout()
        self.main_panel.addLayout(self.header_panel)

        # creating header panel buttons
        self.character_display_panel = QtGui.QLabel("Enter Text!")
        self.start_button = QtGui.QPushButton("Start")
        self.end_button = QtGui.QPushButton("Pause")

        # setting button click listeners
        self.start_button.clicked.connect(self.start())
        self.end_button.clicked.connect(self.pause_resume())

        # adding buttons to header panel
        self.header_panel.addWidget(self.character_display_panel)
        self.header_panel.addWidget(self.start_button)
        self.header_panel.addWidget(self.end_button)

        # adding keyboard gui to main panel
        # creating a button grid
        self.grid = QtGui.QGridLayout()
        self.grid.setSpacing(0)
        self.keyboard = Keyboard(self.main_panel, self.character_display_panel,
                                 self.interval)

        # setting layout to main_panel
        self.setLayout(self.main_panel)

    # signal functions (on click listeners)
    # -------------------------------------
    def start(self):
        def start_function():
            # setting / resetting variables
            self.start_button.setDisabled(True)
            self.controller.resume()
            print(self.controller)
            self.keyboard.start()

        return start_function

    def pause_resume(self):
        # print("Pause resume")

        def pause_resume_function():

            button_pause_resume = self.end_button
            print("Before pause-resume")
            print(self.controller)
            if button_pause_resume.text() == "Pause":
                button_pause_resume.setText("Resume")
                self.controller.pause()
                self.keyboard.pause()
            else:
                button_pause_resume.setText("Pause")
                self.controller.resume()
                self.keyboard.resume()
            print("After pause-resume")
            print(self.controller)

        return pause_resume_function

    def closeEvent(self, event):
        self.controller.quit()
        print("Exiting...")
        event.accept()
Ejemplo n.º 18
0
from Move import Move
from Keyboard import Keyboard
from Render import Render
from Game import run_game_lose

pygame.init()

screen = pygame.display.set_mode((400, 400))
pygame.display.set_caption('2048')

font = pygame.font.Font('font/ahronbd.ttf', 50)


move = Move()
move.generate_structure()
keyboard = Keyboard()
render = Render()
cont = True
game_lose = False
while cont:
	screen.fill(h333)
	key = keyboard.check()
	
	if key == "down":
		move.down()
	elif key == "up":
		move.up()
	elif key == "left":
		move.left()
	elif key == "right":
		move.right()
Ejemplo n.º 19
0

pygame.init()

scale = 0.5  # 1 - trybus, 0.5 glos

width = int(1920 * scale)
height = int(1080 * scale)

win = pygame.display.set_mode((width, height))
screen = pygame.display.set_caption("My Awesome Game")
bg = pygame.image.load(os.path.join(os.getcwd(), "Assets", "bg1Art.png"))
bg = pygame.transform.rotozoom(bg, 0, scale)
#bg = pygame.image.load(".Assets/bg1Art.png")

K = Keyboard()
G = Ground()
P = Player(G=G)

run = True
while run:
    pygame.time.delay(20)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    K.keyboard(pygame, P)

    myUpdate(P, G)

    #print(P.ay, P.vy)
Ejemplo n.º 20
0
class PlaylistMgr:
	def __init__(self, app, done=1, skin=None):
		self.app = app
		self.playlistdir = self.app.opts['playlistdir']
		print "Playlistdir = %s" % self.playlistdir
		self.sdb = app.sdb
		self.plmDone = done
		self.kbd = Keyboard(app, done=KBD_DONE, cancel=KBD_CANCEL, skin=skin)
		self.playlists = []
		self.loadPlaylists()
		#self.buildPLMenu()
		self.menu = []
		self.active = False
		self.plIndex = None
		self.clearPending = False
		self.chosenPlaylist = None
		self.albumToAdd = None
		self.artistToAdd = None
		self.songToAdd = None
		self.normalMessage = ""
		self.ple = PLEdit(app)
		
	def loadPlaylists(self):
		if not os.path.isdir(self.playlistdir):
			print "Creating playlists directory: %s" % self.playlistdir
			os.mkdir(self.playlistdir)
		
		if not os.access(self.playlistdir, os.W_OK):
			raise PlaylistError("Cannot write into playlist directory: %s" % self.playlistdir)	
		
		files = os.listdir(self.playlistdir)
		jplFiles = []
		for name in files:
			#if name.startswith("."): continue
			fname, fext = os.path.splitext(name)
			if fext.lower() != ".jpl": continue
			
			pl = PlayList(fname)
			jplFiles.append(fname)
			fn = os.path.join(self.playlistdir, name)
			for line in file(fn, 'U'):
				l = line.strip()
				if l.startswith('#') or len(l) == 0:
					continue
				
				so = self.sdb.getSongByFile(l)
				if not so:
					print "Playlist %s, no file with filename %s - skipping" % (name, l)
				else:
					pl.addSong(so)
			
			self.playlists.append(pl)
			
		for name in files:
			#if name.startswith("."): continue
			fname, fext = os.path.splitext(name)
			if fext.lower() != ".m3u": continue
			
			if fname in jplFiles:
				print "skipping duplicate named M3U file %s" % fname
				continue
			
			pl = PlayList(fname)
			fn = os.path.join(self.playlistdir, name)
			for line in file(fn, 'U'):
				l = line.strip()
				if l.startswith('#') or len(l) == 0:
					continue
				
				so = self.sdb.getSongByFile(l)
				if not so:
					print "Playlist %s, no file with filename %s - skipping" % (name, l)
				else:
					pl.addSong(so)
			
			self.playlists.append(pl)
		
		self.sortPlayLists()
			
	def sortPlayLists(self):
		s = sorted(self.playlists, cmpPlayLists)
		self.playlists = s
			
	def delPlaylistFile(self, name):
		path = os.path.join(self.playlistdir, name + ".jpl")

		try:
			print "Attempting to delete (%s)" % path
			os.remove(path)
		except:
			print "delete failed"
					
	def savePlaylists(self):
		for p in self.playlists:
			self.savePlaylist(p)
			
	def savePlaylist(self, pl):
		fn = os.path.join(self.playlistdir, pl.getName() + ".jpl")
		try:
			fp = open(fn, "w")
		except:
			print "Error opening playlist file %s for output" % fn
		else:
			for s in pl:
				fp.write("%s\n" % s.getFile())
			fp.close()
			
		# remove corresponding m3u file if it exists
		# 		fn = os.path.join(self.playlistdir, pl.getName() + ".m3u")
		# 		
		# 		try:
		# 			os.remove(fn)
		# 		except:
		# 			pass
							
	def buildPLMenu(self):
		menu = []
		i = 0
		menu.append(["Add New Playlist", -1, True, ""])
		self.normalMessage = "Press PLAY to play Playlist, CLEAR to delete"
		if self.app.nowPlaying.isActive():
			if not self.selectonly:
				menu.append(['"Now Playing"', -2, True, ""])
				self.normalMessage = 'Press PLAY to play Playlist, CLEAR to delete, ENTER to Add to "Now Playing" Playlist'
			
		for p in self.playlists:
			menu.append(["%s (%d)" % (p.getName(), len(p)), i, True, self.normalMessage])
			i += 1
			
		self.menu = Menu(menu)
		
	def activate(self, selectonly=False, done=None, album=None, artist=None, song=None, playlist=None):
		self.albumToAdd = album
		self.artistToAdd = artist
		self.songToAdd = song
		self.playlistToAdd = playlist
		
		self.selectonly = selectonly
		
		if self.active:
			return
		
		if done:
			self.plmDone = done
			
		self.buildPLMenu()
			
		m, self.plIndex = self.app.mm.Descend(self.menu)
		self.active = True
		
	def deactivate(self):
		if not self.active:
			return
		self.app.mm.Ascend()
		self.active = False
		
	def isActive(self):
		return self.active
	
	def handle_key_press(self, keynum, rawcode):
		if self.kbd.isActive():
			self.kbd.handle_key_press(keynum, rawcode)
			return
		
		if self.ple.isActive():
			self.ple.handle_key_press(keynum, rawcode)
			return
		
		if self.app.mm.isNavKey(keynum, rawcode):
			if self.clearPending:
				self.clearPending = False
				self.app.setMessage(self.normalMessage)
				
			m, self.plIndex = self.app.mm.Navigate(keynum, rawcode)
			return
			
		if keynum != KEY_CLEAR:
			if self.clearPending:
				self.clearPending = False
				self.app.setMessage(self.normalMessage)
			
		if keynum == KEY_CLEAR:
			value = self.menu.getMenuValue(self.plIndex)
			if value in [ -1, -2 ]:
				self.app.sound('bonk')
				
			else:
				if self.clearPending:
					if value >= 0 and value < len(self.playlists):
						self.delPlaylistFile(self.playlists[value].getName())
						del self.playlists[value]
						self.buildPLMenu()
						self.app.mm.ReplaceMenu(self.menu)
						
					self.clearPending = False
					self.app.sound('updown')

				else:
					self.clearPending = True
					self.app.sound('alert')
					self.app.setMessage(DEL_CONFIRM_MESSAGE)
				
		elif keynum == KEY_TIVO:
			if rawcode == KBD_DONE:
				s = self.kbd.getResult()
				if s != "":
					pl = PlayList(s)
					self.playlists.append(pl)
					self.sortPlayLists()
					self.buildPLMenu()
					self.app.mm.ReplaceMenu(self.menu)
				#self.app.sound('updown')
				
			elif rawcode == KBD_CANCEL:
				self.app.sound('alert')
				
			elif rawcode == PLE_DONE:
				self.buildPLMenu()
				self.app.mm.ReplaceMenu(self.menu)
				self.app.mm.show()
				if self.chosenPlaylist:
					self.savePlaylist(self.chosenPlaylist)
				self.app.setSubTitle("Choose Playlist")
				#self.app.sound('updown')
				
		elif keynum == KEY_LEFT:
			self.app.mm.Ascend()
			self.active = False
			self.app.send_key(KEY_TIVO, self.plmDone)
			self.app.sound('updown')
			
		elif keynum in [ KEY_SELECT, KEY_RIGHT ]:
			value = self.menu.getMenuValue(self.plIndex)
			if value == -1:
				# new playlist
				self.kbd.reset()
				self.kbd.activate()
				
			elif value == -2:
				self.chosenPlaylist = None
				
				changes = False		

				if self.songToAdd:
					self.app.addToNowPlaying(song = self.songToAdd)
					self.songToAdd = None
					changes = True
					
				if self.albumToAdd:
					self.app.addToNowPlaying(album = self.albumToAdd)
					self.albumToAdd = None
					changes = True
					
				if self.playlistToAdd:
					for s in self.playlistToAdd:
						self.app.addToNowPlaying(song = s)
					self.playlistToAdd = None
					changes = True
					
				if self.artistToAdd:
					self.app.addToNowPlaying(artist = self.artistToAdd)
					self.artistToAdd = None
					changes = True
					
				if changes:
					self.buildPLMenu()
					self.app.mm.ReplaceMenu(self.menu)
	
				self.app.mm.hide()	
				self.ple.browse(self.app.NPPlaylist, done=PLE_DONE)
				
			else:
				self.chosenPlaylist = self.playlists[value]
				
				changes = False
				
				if self.songToAdd:
					self.chosenPlaylist.addSong(self.songToAdd)
					self.songToAdd = None
					changes = True
					
				if self.albumToAdd:
					for s in self.albumToAdd:
						self.chosenPlaylist.addSong(s)
					self.albumToAdd = None
					changes = True
					
				if self.playlistToAdd:
					for s in self.playlistToAdd:
						self.chosenPlaylist.addSong(s)
					self.playlistToAdd = None
					changes = True
					
				if self.artistToAdd:
					for s in self.artistToAdd:
						self.chosenPlaylist.addSong(s)
					self.artistToAdd = None
					changes = True
					
				if changes:
					self.buildPLMenu()
					self.app.mm.ReplaceMenu(self.menu)

				if len(self.chosenPlaylist) == 0:
					self.app.sound('bonk')
					return
					
				self.app.mm.hide()			
				self.ple.edit(self.chosenPlaylist, done=PLE_DONE)
				
					
			self.app.sound('updown')
			
		elif keynum == KEY_ENTER:
			if self.selectonly:
				self.app.sound('bonk')
			else:
				value = self.menu.getMenuValue(self.plIndex)
				if value < 0:
					self.app.sound('bonk')
				else:
					self.chosenPlaylist = self.playlists[value]
					self.app.addToNowPlaying(playlist = self.chosenPlaylist)
		
		elif keynum == KEY_PLAY:
			value = self.menu.getMenuValue(self.plIndex)
			if value < 0:
				self.app.sound('bonk')
			else:
				self.chosenPlaylist = self.playlists[value]
				self.app.addToNowPlaying(clear=True, playlist = self.chosenPlaylist)
					
				self.app.nowPlaying.Play(self.app.NPPlaylist,
										shuffle=self.app.opts['playlistshuffle'],
										loop=self.app.opts['playlistloop'])
				
		else:
			self.app.sound('bonk')
Ejemplo n.º 21
0
 def __init__(self):
     self.__parts = [Mouse(), Keyboard(), Monitor()]
Ejemplo n.º 22
0
    def __init__(self, master, valves):
        Frame.__init__(self, master, bg='sky blue', width=1366, height=768)
        self.master = master

        self.canvas = Canvas(self, height=640, width=1300, bg='sky blue')
        self.frame = Frame(self.canvas, bg='sky blue')
        self.frame.bind('<Button-1>', self.process_click_out)

        self.scrollbar = Scrollbar(self, orient='vertical', command=self.canvas.yview)
        self.scrollbar.configure(activebackground='DarkRed', background='red', width=40)
        self.canvas.configure(yscrollcommand=self.scrollbar.set, scrollregion=[0, 0, 1366, 2100])

        self.scrollbar.pack(side='right', fill='y')
        self.canvas.pack(side='left')
        self.canvas.create_window((0, 0), window=self.frame, anchor='nw')

        self.keyboard = Keyboard(self.master)

        self.valves = valves
        self.frame.config(bg='sky blue')
        
        index = 0
        while index < 25:
            self.frame.grid_rowconfigure(index, minsize=80)
            self.frame.grid_columnconfigure(index, minsize=150)
            index += 1

        num_label = [Label(self.frame, text='1'),
                     Label(self.frame, text='2'),
                     Label(self.frame, text='3'),
                     Label(self.frame, text='4'),
                     Label(self.frame, text='5'),
                     Label(self.frame, text='6'),
                     Label(self.frame, text='7'),
                     Label(self.frame, text='8'),
                     ]
        row = 1
        for each in num_label:
            each.grid(row=row, column=0)
            each.config(width=3, font=('Lucida Console', 30), bg='sky blue', fg='RoyalBlue4')
            row += 3

        text_label = [Label(self.frame, text='VALVE 1:  '),
                     Label(self.frame, text='ACTION A: '),
                     Label(self.frame, text='ACTION B: '),

                     Label(self.frame, text='VALVE 2:  '),
                     Label(self.frame, text='ACTION A: '),
                     Label(self.frame, text='ACTION B: '),

                     Label(self.frame, text='VALVE 3:  '),
                     Label(self.frame, text='ACTION A: '),
                     Label(self.frame, text='ACTION B: '),

                     Label(self.frame, text='VALVE 4:  '),
                     Label(self.frame, text='ACTION A: '),
                     Label(self.frame, text='ACTION B: '),

                     Label(self.frame, text='VALVE 5:  '),
                     Label(self.frame, text='ACTION A: '),
                     Label(self.frame, text='ACTION B: '),

                     Label(self.frame, text='VALVE 6:  '),
                     Label(self.frame, text='ACTION A: '),
                     Label(self.frame, text='ACTION B: '),

                     Label(self.frame, text='VALVE 7:  '),
                     Label(self.frame, text='ACTION A: '),
                     Label(self.frame, text='ACTION B: '),

                     Label(self.frame, text='VALVE 8:  '),
                     Label(self.frame, text='ACTION A: '),
                     Label(self.frame, text='ACTION B: ')

                     ]
        row = 1
        for each in text_label:
            each.grid(row=row, column=1)
            each.config(width=12, font=('Lucida Console', 30), bg='sky blue', fg='RoyalBlue4')
            row += 1

        self.valve_label = [Label(self.frame, textvariable=self.valves[0].get_name()),
                            Label(self.frame, textvariable=self.valves[1].get_name()),
                            Label(self.frame, textvariable=self.valves[2].get_name()),
                            Label(self.frame, textvariable=self.valves[3].get_name()),
                            Label(self.frame, textvariable=self.valves[4].get_name()),
                            Label(self.frame, textvariable=self.valves[5].get_name()),
                            Label(self.frame, textvariable=self.valves[6].get_name()),
                            Label(self.frame, textvariable=self.valves[7].get_name())]
        row = 1 
        for each in self.valve_label:
            each.grid(row=row, column=2)
            each.config(width=12, font=('Lucida Console', 30), bg='sky blue', fg='RoyalBlue4', anchor='w')
            each.bind('<Button-1>', self.process_click_out)
            row += 3

        self.entry_field = [Entry(self.frame, text=''),
                            Entry(self.frame, text=''),
                            Entry(self.frame, text=''),
                            Entry(self.frame, text=''),
                            Entry(self.frame, text=''),
                            Entry(self.frame, text=''),
                            Entry(self.frame, text=''),
                            Entry(self.frame, text=''),

                            Entry(self.frame, text=''),
                            Entry(self.frame, text=''),
                            Entry(self.frame, text=''),
                            Entry(self.frame, text=''),
                            Entry(self.frame, text=''),
                            Entry(self.frame, text=''),
                            Entry(self.frame, text=''),
                            Entry(self.frame, text=''),

                            Entry(self.frame, text=''),
                            Entry(self.frame, text=''),
                            Entry(self.frame, text=''),
                            Entry(self.frame, text=''),
                            Entry(self.frame, text=''),
                            Entry(self.frame, text=''),
                            Entry(self.frame, text=''),
                            Entry(self.frame, text='')
                            ]
        row = 1
        for each in self.entry_field:
            each.grid(row=row, column=3)
            each.config(width=12, font=('Lucida Console', 30), bg='sky blue', fg='RoyalBlue4')
            each.bind('<Button-1>', self.process_click_in)
            row += 1

        self.action_a_label = [Label(self.frame, textvariable=self.valves[0].get_action_a()),
                               Label(self.frame, textvariable=self.valves[1].get_action_a()),
                               Label(self.frame, textvariable=self.valves[2].get_action_a()),
                               Label(self.frame, textvariable=self.valves[3].get_action_a()),
                               Label(self.frame, textvariable=self.valves[4].get_action_a()),
                               Label(self.frame, textvariable=self.valves[5].get_action_a()),
                               Label(self.frame, textvariable=self.valves[6].get_action_a()),
                               Label(self.frame, textvariable=self.valves[7].get_action_a())
                               ]
        row = 2
        for each in self.action_a_label:
            each.grid(row=row, column=2)
            each.config(width=12, font=('Lucida Console', 30), bg='sky blue', fg='RoyalBlue4', anchor='w')
            each.bind('<Button-1>', self.process_click_out)
            row += 3

        self.action_b_label = [Label(self.frame, textvariable=self.valves[0].get_action_b()),
                               Label(self.frame, textvariable=self.valves[1].get_action_b()),
                               Label(self.frame, textvariable=self.valves[2].get_action_b()),
                               Label(self.frame, textvariable=self.valves[3].get_action_b()),
                               Label(self.frame, textvariable=self.valves[4].get_action_b()),
                               Label(self.frame, textvariable=self.valves[5].get_action_b()),
                               Label(self.frame, textvariable=self.valves[6].get_action_b()),
                               Label(self.frame, textvariable=self.valves[7].get_action_b())
                               ]

        row = 3
        for each in self.action_b_label:
            each.grid(row=row, column=2)
            each.config(width=12, font=('Lucida Console', 30), bg='sky blue', fg='RoyalBlue4', anchor='w')
            each.bind('<Button-1>', self.process_click_out)
            row += 3

        self.lock()
import os
import re
import pyautogui
from Keyboard import Keyboard
from scipy.spatial import distance
from imutils import face_utils
from keras.models import load_model
from fr_utils import *
from inception_blocks_v2 import *

import time

from Quartz import CGSessionCopyCurrentDictionary

password = '******'
keyboard = Keyboard(password)

detector = dlib.get_frontal_face_detector()

FRmodel = load_model('face-rec.h5')
print("Total Params:", FRmodel.count_params())
predictor = dlib.shape_predictor("shape_predict_68_face_landmarks.dat")
thresh = 0.15


def eye_aspect_ratio(eye):
    A = distance.euclidean(eye[1], eye[5])
    B = distance.euclidean(eye[2], eye[4])
    C = distance.euclidean(eye[0], eye[3])
    ear = (A + B) / (2.0 * C)
    return ear
Ejemplo n.º 24
0
 def set_type(self):
     self.type = Keyboard()
     self.key_set = self.type.key_set
     self.del_key_set = self.type.del_key_set
Ejemplo n.º 25
0
def show_builder(chat_id):
    keyboard = Keyboard()
    keyboard.addButtons(["Test1", "Test2"])
    keyboard.setOneTimeKeyboard(True)
    keyboard.setRowWidth(2)
    keyboard.shouldKeyboardBeResized(True)
    bot.send_message(chat_id,
                     "Choose one letter:",
                     reply_markup=keyboard.getResult())
Ejemplo n.º 26
0
import pygame
from Keyboard import Keyboard
from Renderer import Renderer
from Wheel import Wheel
from Car import Car
from NewGround import NewGround
from Physics import Vector, Point, Function

# init

R = Renderer(1000, 500)
K = Keyboard()
NG = NewGround()
ground_display = 500 / R.scale

WF = Wheel(NG, 128, -800)  # front wheel
WB = Wheel(NG, 0, -800)  # back wheel
C = Car(WB, WF)

run = True

# main loop

while run:
    R.delay(20)

    # event handle
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False
        K.check(C)