コード例 #1
0
ファイル: user.py プロジェクト: vbraun/sagepad
 def get_pad(self, pad_id):
     if not isinstance(pad_id, ObjectId):
         pad_id = Pad.make_id(pad_id)
     if pad_id == self._current_pad_id:
         return self.get_current_pad()
     pad = Pad.lookup(pad_id, self)
     return pad
コード例 #2
0
ファイル: main.py プロジェクト: stasio14/pong
def run_game():
    """main loop of the game"""
    #intialization of pygame library
    pygame.init()
    #initializing all needed objects
    settings = Settings()
    screen = pygame.display.set_mode(
        (settings.screen_width, settings.screen_height))
    ball = Ball(screen)
    pad = Pad(settings, screen)
    pad1 = Pad1(settings, screen)
    stats = Game_stats(settings)
    pygame.display.set_caption("Pong")
    sb = Scoreboard(screen, stats)
    sb1 = Scoreboard1(screen, stats)
    start_button = Button(screen, settings, "START")

    while True:
        #using functions from module
        gf.check_events(settings, screen, pad, pad1, stats, start_button)
        gf.update_screen(settings, screen, pad, pad1, ball, stats,
                         start_button, sb, sb1)
        if stats.game_active:
            pad.update(settings)
            pad1.update(settings)
            gf.update_ball(ball, settings, pad, pad1, stats, sb, sb1)
コード例 #3
0
def get_all_monsters(verbose=False):
    """ outputs all monsters' complete stats """
    padpy = Pad(verbose=verbose)

    monsters = padpy.get_all_monsters()
    for monster in monsters:
        padpy.pretty_print(monster)
        print
コード例 #4
0
ファイル: main.py プロジェクト: paperCut11/pong
	def __init_canva(self):
		# Canvas object
		self.c = ExCanvas(self.root, width=self.ss.WIDTH, 
							height=self.ss.HEIGHT, background=self.theme["bg"])
		self.c.pack()#expand=True)
		 
		# central line
		self.c.create_line(self.ss.WIDTH//2, 0, self.ss.WIDTH//2, 
							self.ss.HEIGHT, fill=self.theme["line"], tag="line")
							
		self.c.create_ball(self.ss.WIDTH//2, self.ss.HEIGHT//2, self.ss.BALL_RADIUS/2, 
							fill=self.theme["line"], width=0, tag="line")
		
		
		self.__init_players_score()
		
		# Work with Pads
		left_pad_id = self.c.create_rectangle(0, 0, self.ss.PAD_W, 
											self.ss.PAD_H, width=1, 
											fill=self.theme["l_pad"], tag="l_pad")
		 
		right_pad_id = self.c.create_rectangle(self.ss.WIDTH-self.ss.PAD_W, 0, self.ss.WIDTH, 
									  		self.ss.PAD_H, width=1, 
									  		fill=self.theme["r_pad"], tag="r_pad")
								  
		self.left_pad = Pad(left_pad_id, self.c, self.ss, ("w", "s"), Player.LEFT)
		self.right_pad = Pad(right_pad_id, self.c, self.ss, ("Up", "Down"), Player.RIGHT)
		
		self.player = Player(self.left_pad, self.right_pad)
		
		self.ball = Ball(self.c, self.player, self, self.ss, self.theme["ball"])
		
		
		self.buffs = Buffs(self.ss, self)
		
		# Menu creating
		stop_menu_id = self.c.create_window((self.ss.WIDTH/2, self.ss.HEIGHT/2))
		self.stop_menu = StopMenu(stop_menu_id, self)
		self.c.itemconfig(stop_menu_id, window=self.stop_menu, state=HIDDEN)
		
		options_menu_id = self.c.create_window((self.ss.WIDTH/2, self.ss.HEIGHT/2))
		self.options_menu = OptionMenu(options_menu_id, self)
		self.c.itemconfig(options_menu_id, window=self.options_menu, state=HIDDEN)
		
		start_menu_id = self.c.create_window((self.ss.WIDTH/2, self.ss.HEIGHT/2))
		self.start_menu = StartMenu(start_menu_id, self)
		self.c.itemconfig(start_menu_id, window=self.start_menu) 
		
		self.cur_menu = self.start_menu
										  
		self.c.focus_set()
		self.theme.set_canvas(self.c)
		
		self.c.bind("<KeyPress>", self._key_pressed)
		self.c.bind("<KeyRelease>", self._key_released)
		
		self.game_stopped = True
コード例 #5
0
def get_events(verbose=False):
    """ 
    Gets all the events returned by the PADherder API. 
    Generally a few days worth.

    Note that these are cached, you'll need to delete data/events.json manually 
    if you want an updated list of events.
    """
    padpy = Pad(verbose=verbose)

    for evt in padpy.get_all_events():
        print evt
コード例 #6
0
class ExampleWindow(QMainWindow): #класс окна
	
	def __init__(self):
		super().__init__()
		self.setMinimumSize(QSize(800, 600))
		self.setWindowTitle('Пришельцы')
		central_widget = QWidget(self)
		self.alien_timer = QBasicTimer() #таймер
		self.setCentralWidget(central_widget)
		self.sd = Sd(QtWidgets.QLabel(self), 'sd.png', 400, 550) #создаем экземпляр класса Sd с атрибутами (obj, pic_name, x, y) где obj? это лэйбл
		self.pad_l = Pad(QtWidgets.QLabel(self), 'pad.png', 10, 550) #создаем экземпляр класса Pad с атрибутами (obj, pic_name, x, y) где obj? это лэйбл
		self.numbers = 30
		self.aliens_labl = [] # создаем список и заполняем его лейбами
		for i in range(self.numbers):
			self.aliens_labl.append(QtWidgets.QLabel(self))

		self.al = Aliens(self.aliens_labl, 'alien.png') #создаем экземпляр класса Aliens с атрибутами списка состоящего из лейб
		self.alien_timer.start(100, self)	#запускаем таймер


	def keyPressEvent(self, event):	

		if event.key() == QtCore.Qt.Key_D:
			self.pad_l.move(10)	# запускаем экземпляр класса Pad, его метод move, с атрибутом pad_step равным 10 
		if event.key() == QtCore.Qt.Key_A:
			self.pad_l.move(-10)	
		if event.key() == QtCore.Qt.Key_S and self.sd.y == 540: # условие, чтобы не отстреливать всех пришельцев подряд
			self.sd.move() # запускаем метод, в котором содержится только совершение выстрела

	def dialogs(self): # метод диалоговых окон

		if len(self.al.aliens) == 0: # если в списке пришельцев не осталось
			self.gameover = QMessageBox.question(main_window, 'конец игры !!!!!!', 'Победа. \n Попробовать снова?', QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes)
			if self.gameover == QMessageBox.Yes:					
				self.al = Aliens(self.aliens_labl, 'alien.png')	 # презапуск класса с пришельцами
			else:
				sys.exit(app.exec_())
		
		if self.al.aliens[len(self.al.aliens)-1].y >= 550: # если координаты по y последнего (в списке) прешельца больше чем 550
			self.gameover = QMessageBox.question(main_window, 'конец игры !!!!!!', 'Пришельцы нас захватили. \n Попробовать снова?', QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes)
			if self.gameover == QMessageBox.Yes:					
				self.al = Aliens(self.aliens_labl, 'alien.png')	# презапуск класса с пришельцами				
			else:
				sys.exit(app.exec_())		

	def timerEvent(self, e):
		self.dialogs() # запускаем метод диалогов
		self.al.tic() # запускаем пришельцев
		self.sd.tic(10, self.pad_l.x, self.pad_l.y) # первый атрибут определяет скорость выстрела
		self.sd.shoot(self.al.aliens) # проверяем совпадение sd и пришельца
コード例 #7
0
def calc_xp(monster_id, level, verbose=False):
    """ calculates XP required from level 1 to level """
    padpy = Pad(verbose=verbose)

    monster = padpy.get_monster(monster_id)
    calc_level = min(level, monster.max_level)
    if calc_level != level:
        print "{monster} is level capped at {max}!".format(
                monster=monster,
                max=monster.max_level,
        )

    print "From level 1 to level %s" % calc_level
    print "%s XP is required" % monster.xp_curve.calc_for_level(level)
コード例 #8
0
ファイル: connection.py プロジェクト: zosiakropka/academia
    def handle_message(self, record):
        """
        Try to decode messge record and process it adequately. Should be
        called by handle_read() when receiving single record is complete.
        """
        data = decode(record)
        if data and "purpose" in data:
            logging.debug("%s has data onboard, purpose: %s" % (self.CHNL, data["purpose"]))
            purpose = data["purpose"]
            if purpose == "pad" and "message" in data:
                self.pad_id = data.pop("message")
                self.pad = Pad(self.pad_id)
            elif purpose == "patches" and "message" in data and self.pad_id:
                try:
                    token = data.pop("token", None)
                    tokens.validate(
                        token,
                        scope.access_obj(Note.objects.get(pk=self.pad_id), "edit"),
                    )
                    data["message"] = self.pad.process(data["message"])

                    self.pad_broadcast(data)
                except Exception:
                    response = {
                        "purpose": "auth",
                        "message": "fail"
                    }
                    self.send_record(response)
コード例 #9
0
	def __init__(self):
		super().__init__()
		self.setMinimumSize(QSize(800, 600))
		self.setWindowTitle('Пришельцы')
		central_widget = QWidget(self)
		self.alien_timer = QBasicTimer() #таймер
		self.setCentralWidget(central_widget)
		self.sd = Sd(QtWidgets.QLabel(self), 'sd.png', 400, 550) #создаем экземпляр класса Sd с атрибутами (obj, pic_name, x, y) где obj? это лэйбл
		self.pad_l = Pad(QtWidgets.QLabel(self), 'pad.png', 10, 550) #создаем экземпляр класса Pad с атрибутами (obj, pic_name, x, y) где obj? это лэйбл
		self.numbers = 30
		self.aliens_labl = [] # создаем список и заполняем его лейбами
		for i in range(self.numbers):
			self.aliens_labl.append(QtWidgets.QLabel(self))

		self.al = Aliens(self.aliens_labl, 'alien.png') #создаем экземпляр класса Aliens с атрибутами списка состоящего из лейб
		self.alien_timer.start(100, self)	#запускаем таймер
コード例 #10
0
    def _read_pad_definition(self, data):
        """
        Read the pad info from a line
        :param dict data: the dict which includes the pad info
        :return:
        """
        layers = ['TOP', 'BOTTOM']

        if data['LAYER'] not in layers:
            return

        padname = data['PAD_NAME']

        if self.pads.has_key(padname):
            self.pads[padname].append(Pad(data))
        else:
            self.pads[padname] = [Pad(data)]
コード例 #11
0
ファイル: statusbar.py プロジェクト: cenmmy/cenmmyChat
 def __init__(self,
              stdscr,
              nlines,
              ncols,
              sminrow,
              smincol,
              smaxrow,
              smaxcol,
              mode="NORMAL",
              other="",
              fgcolor=curses.COLOR_WHITE,
              bgcolor=curses.COLOR_BLACK,
              color_pair=5):
     Pad.__init__(self, stdscr, nlines, ncols, sminrow, smincol, smaxrow,
                  smaxcol, fgcolor, bgcolor, color_pair)
     self.mode = mode
     self.other = other
     self.smile = '☺'
コード例 #12
0
def create_fixed_length_left_padded_string(context):
    assert (context.source_string is None) is False
    assert (context.padding_character is None) is False
    assert (context.output_length is None
            or context.output_length == 0) is False

    context.left_padded_output = Pad.left(context.source_string,
                                          context.padding_character,
                                          context.output_length)
    print("left_padded_output: " + context.left_padded_output)
    assert (context.left_padded_output is None) is False
コード例 #13
0
def calc_attribute(monster_id, level, attribute, plus=0, verbose=False):
    """ 
    calculates the value for a given attribute at a given level (with plus values) 
    """
    padpy = Pad(verbose=verbose)

    monster = padpy.get_monster(monster_id)
    calc_level = min(level, monster.max_level)
    if calc_level != level:
        print "{monster} is level capped at {max}!".format(
                monster=monster,
                max=monster.max_level,
        )

    attr = AttributeTypes[attribute]
    attr_obj = monster.get_attribute(attr)

    result = attr_obj.calc_for_level_plus(calc_level, plus)
    print "Attribute %s at level %s plus %s" % (attr_obj, calc_level, plus)
    print "%s is the stat" % (result)
コード例 #14
0
ファイル: user.py プロジェクト: vbraun/sagepad
 def get_current_pad(self):
     """
     The current pad always exists; A new one is created if necessary.
     """
     if self._current_pad_id is None:
         cursor = Pad.iterate(self, 1)
         try:
             self._current_pad = cursor.next()
         except StopIteration:
             self._current_pad = Pad.make(self.get_id())
         self._current_pad_id = self._current_pad.get_id()
         self.save()
     if self._current_pad is None:
         try:
             pad = Pad.lookup(self._current_pad_id, self)
         except PadInvalidId:
             pad = Pad.make(self)
         self._current_pad = pad
         self._current_pad_id = self._current_pad.get_id()
         self.save()
     return self._current_pad
コード例 #15
0
ファイル: user.py プロジェクト: vbraun/sagepad
    def set_current_pad(self, pad):
        """
        Set the currently active pad

        INPUT: 

        - ``pad`` -- a :class:`pad.Pad` or a pad id (:class:`ObjectId`
          or string).

        Throws `PadInvalidId` if ``pad`` does not exists.
        """
        if isinstance(pad, basestring):
            pad = Pad.make_id(pad)
        if isinstance(pad, ObjectId):
            if pad == self._current_pad_id:
                return
            pad = Pad.lookup(pad, self)
        if pad.get_id() == self._current_pad_id:
            return
        self._current_pad = pad
        self._current_pad_id = pad.get_id()
        self.save()
コード例 #16
0
class WacomGui(QMainWindow, wacom_menu.Ui_MainWindow):
    buttonClicked = pyqtSignal(int)
    def __init__(self, parent=None):
        super(WacomGui, self).__init__(parent)
        self.setupUi(self)
        self.toggle = False
        self.load = False
        self.cwd = os.path.dirname(os.path.abspath(__file__))
        if self.cwd == '/usr/local/bin':
            self.cwd = '/usr/local/wacom-gui'
        self.setFocusPolicy(Qt.NoFocus)
        # button instances
        self.tabletButtons = ButtonGroup()
        self.toolButtons = ButtonGroup()
        self.configButtons = ButtonGroup()
        # button layouts
        self.tabletLayout = ButtonLayout()
        self.toolLayout = ButtonLayout()
        self.configLayout = ButtonLayout()
        self.tabletScroll.setWidget(self.tabletLayout.frame)
        self.toolScroll.setWidget(self.toolLayout.frame)
        self.configScroll.setWidget(self.configLayout.frame)
        # config files
        self.configs = {}
        # hold current device info
        self.dev = None
        self.dev_id = None
        self.config = None
        # load widgets
        self.pad = Pad()
        self.pad.hide()
        self.stylus = Stylus()
        self.stylus.hide()
        self.touch = Touch()
        self.touch.hide()
        # ui icon
        self.tabletRefresh.setIcon(QIcon(os.path.join(self.cwd, os.path.join(self.cwd, 'icons/ui/refresh.png'))))
        # get connected tablet info
        self.tablet_data = Tablets()
        # attach function to refresh tablets
        self.tabletRefresh.clicked.connect(self.refreshTablets)
        # add buttons for connected tablets
        self.initTabletButtons()
        # generate tool buttons
        self.initToolButtons()
        # add/remove button functions
        self.addConfig.setEnabled(True)
        self.addConfig.clicked.connect(self.newConfig)
        self.removeConfig.clicked.connect(self.verifyConfigRemove)
        # about/help menu
        self.aboutButton.clicked.connect(About.display)
        # refresh tablet list, set tools, configs
        self.refreshTablets()
        self.controlBox.setContentsMargins(0, 0, 0, 0)
        # add control widgets to control box
        hbox = QHBoxLayout()
        hbox.setAlignment(Qt.AlignHCenter)
        hbox.addWidget(self.pad)
        hbox.addWidget(self.stylus)
        hbox.addWidget(self.touch)
        self.controlBox.setLayout(hbox)
        # save config button
        self.saveConfig.clicked.connect(self.updateConfigs)
        # configure device reset button
        self.deviceDefaults.clicked.connect(self.deviceReset)
        # load first tool found
        self.toolSelect(self.toolButtons.btn_grp.checkedId())
        # init button functions
        self.tabletButtons.btn_grp.buttonClicked['int'].connect(self.tabletSelect)
        self.toolButtons.btn_grp.buttonClicked['int'].connect(self.toolSelect)
        self.configButtons.btn_grp.buttonClicked['int'].connect(self.configSelect)

    def initTabletButtons(self):
        for dev, data in self.tablet_data.tablets.items():
            for dev_id, tablet in enumerate(data):
                icon = os.path.join(self.cwd, "icons/devices/%spng" % tablet['svg'][:-3])
                if not os.path.isfile(os.path.join(os.getcwd(), icon)):
                    icon = os.path.join(self.cwd, 'icons/devices/generic.png')
                self.tabletLayout.addButton(self.tabletButtons.addButton(tablet['cname'], tablet['pad']['id'],
                                                                         str(dev), dev_id, icon))

    def refreshTablets(self):
        self.tablet_data.get_connected_tablets()
        # clear current tablets from layout
        self.tabletLayout.removeButtons()
        self.tabletButtons.removeButton()
        self.initTabletButtons()
        if self.tabletButtons.buttons.items().__len__() == 0:
            self.toolButtons.hideButtons()
        else:
            self.tabletSelect(0)

    def initToolButtons(self):
        # Functions/Stylus/Touch/Cursor
        self.toolLayout.addButton(self.toolButtons.addButton("Functions", 0, 0, 0, os.path.join(self.cwd, 'icons/ui/functions.png'), 48, True))
        self.toolLayout.addButton(self.toolButtons.addButton("Stylus",  0, 0, 0, os.path.join(self.cwd, 'icons/ui/stylus.png'), 48, True))
        self.toolLayout.addButton(self.toolButtons.addButton("Touch",  0, 0, 0, os.path.join(self.cwd, 'icons/ui/touch.png'), 48, True))
        self.toolLayout.addButton(self.toolButtons.addButton("Mouse", 0, 0, 0, os.path.join(self.cwd, 'icons/ui/mouse.png'), 48, True))

    def setToolsAvail(self, idx):
        self.dev = self.tabletButtons.buttons[(idx, 1)]
        self.dev_id = self.tabletButtons.buttons[(idx, 3)]
        if 'pad' in self.tablet_data.tablets[self.dev][self.dev_id].keys():
            self.toolButtons.buttons[(0, 0)].setVisible(True)
            self.toolButtons.buttons[(0, 1)] = self.dev
            self.toolButtons.buttons[(0, 2)] = self.tablet_data.tablets[self.dev][self.dev_id]['pad']['id']
            self.toolButtons.buttons[(0, 3)] = self.dev_id
        else:
            self.toolButtons.buttons[(0, 0)].setVisible(False)
            self.toolButtons.buttons[(0, 1)] = 0
            self.toolButtons.buttons[(0, 2)] = 0
            self.toolButtons.buttons[(0, 3)] = 0
        if 'stylus' in self.tablet_data.tablets[self.dev][self.dev_id].keys():
            self.toolButtons.buttons[(1, 0)].setVisible(True)
            self.toolButtons.buttons[(1, 1)] = self.dev
            self.toolButtons.buttons[(1, 2)] = [self.tablet_data.tablets[self.dev][self.dev_id]['stylus']['id'],
                                                self.tablet_data.tablets[self.dev][self.dev_id]['eraser']['id']]
            self.toolButtons.buttons[(1, 3)] = self.dev_id
        else:
            self.toolButtons.buttons[(1, 0)].setVisible(False)
            self.toolButtons.buttons[(1, 1)] = 0
            self.toolButtons.buttons[(1, 2)] = 0
            self.toolButtons.buttons[(1, 3)] = 0
        if 'touch' in self.tablet_data.tablets[self.dev][self.dev_id].keys():
            self.toolButtons.buttons[(2, 0)].setVisible(True)
            self.toolButtons.buttons[(2, 1)] = self.dev
            self.toolButtons.buttons[(2, 2)] = self.tablet_data.tablets[self.dev][self.dev_id]['touch']['id']
            self.toolButtons.buttons[(2, 3)] = self.dev_id
        else:
            self.toolButtons.buttons[(2, 0)].setVisible(False)
            self.toolButtons.buttons[(2, 1)] = 0
            self.toolButtons.buttons[(2, 2)] = 0
            self.toolButtons.buttons[(2, 3)] = 0
        if 'cursor' in self.tablet_data.tablets[self.dev][self.dev_id].keys():
            self.toolButtons.buttons[(3, 0)].setVisible(True)
            self.toolButtons.buttons[(3, 1)] = self.dev
            self.toolButtons.buttons[(3, 2)] = self.tablet_data.tablets[self.dev][self.dev_id]['cursor']['id']
            self.toolButtons.buttons[(3, 3)] = self.dev_id
        else:
            self.toolButtons.buttons[(3, 0)].setVisible(False)
            self.toolButtons.buttons[(3, 1)] = 0
            self.toolButtons.buttons[(3, 2)] = 0
            self.toolButtons.buttons[(3, 3)] = 0

    def deviceReset(self):
        self.pad.set_default()
        self.stylus.resetPen()
        self.stylus.resetEraser()
        self.stylus.mapping.resetMapping()
        self.touch.reset()
        # TODO: add other resets

    def emptyConfig(self, dev, dev_id):
        config = {}
        for input in self.tablet_data.tablets[dev][dev_id].keys():
            if input in ['pad', 'stylus', 'eraser', 'touch', 'cursor']:
                config[input] = {}
                if input in ['pad', 'stylus', 'eraser']:
                    config[input]['buttons'] = {}
                    if input == 'pad':
                        buttons = self.tablet_data.tablets[dev][dev_id][input]['buttons']
                        for button in buttons.keys():
                            config['pad']['buttons'][button] = 'Default'
        return config

    def verifyConfigRemove(self):
        reply = QMessageBox.question(self, 'Remove Config',
                                     "Delete \"%s\" config file?" % self.config,
                                     QMessageBox.Yes, QMessageBox.No)
        if reply == QMessageBox.Yes:
            home = "%s/.wacom-gui" % expanduser("~")
            conf_path = os.path.join(home, "%s/%s.json" % (self.dev, self.config))
            # delete file
            try:
                os.remove(conf_path)
            except Exception as e:
                print e
            del self.configs[self.dev][self.config]
            self.getConfigs(0)

    def newConfig(self):
        config = AddConfig.add_config(self.configs[self.dev].keys())
        if config is not None:
            # empty config
            self.configs[self.dev][config] = self.emptyConfig(self.dev, self.dev_id)
            # add button
            self.configLayout.addButton(
                self.configButtons.addButton(config, 0, 0, 0, os.path.join(self.cwd, 'icons/ui/config.png'), 48))
            self.config = config
            self.loadConfig(self.dev, self.dev_id, self.config)
            for idx, button in enumerate(self.configButtons.btn_grp.buttons()):
                if button.text() == self.config:
                    self.configButtons.btn_grp.buttons()[idx].setChecked(True)
            self.tablet_data.tablets[self.dev][self.dev_id]['config'] = self.config
            self.removeConfig.setEnabled(True)

    def getConfigs(self, idx):
        self.configLayout.removeButtons()
        self.configButtons.removeButton()
        dev = self.tabletButtons.buttons[(idx, 1)]
        dev_id = self.tabletButtons.buttons[(idx, 3)]
        home = "%s/.wacom-gui" % expanduser("~")
        conf_path = os.path.join(home, dev)
        self.tablet_data.tablets[dev][dev_id]['conf_path'] = os.path.join(home, dev)
        if dev not in self.configs.keys():
            self.configs[dev] = {}
        if os.path.exists(conf_path):
            # get configs in path
            for config in os.listdir(conf_path):
                if os.path.isfile(os.path.join(conf_path, config)) and config.endswith(".json"):
                    with open(os.path.join(conf_path, config), 'r') as f:
                        self.configs[dev][os.path.splitext(config)[0]] = json.load(f)
            # TODO: allow user to sent alternate config to load by default
            # load default config, if it exists
            if 'default' not in self.configs[dev].keys():
                self.configs[dev]['default'] = self.emptyConfig(dev, dev_id)
            # get default config to load for given device, ie last selected config
            self.config = 'default'
            if os.path.exists("%s/device_default" % conf_path):
                with open("%s/device_default" % conf_path, 'r') as f:
                    device = json.load(f)
                # config file exists, use it
                if str(dev_id) in device.keys() and device[str(dev_id)]['config'] in self.configs[dev].keys():
                    self.config = device[str(dev_id)]['config']
                # set defaults in tablet_data, if it's detected
                for idx in device.keys():
                    try:
                        self.tablet_data.tablets[self.dev][int(idx)]['config'] = device[idx]['config']
                    except Exception as e:
                        pass
            self.configLayout.addButton(
                self.configButtons.addButton("default", 0, 0, 0, os.path.join(self.cwd, 'icons/ui/config.png'), 48))
            for config in sorted(self.configs[dev].keys()):
                if config != 'default':
                    self.configLayout.addButton(
                        self.configButtons.addButton(config, 0, 0, 0, os.path.join(self.cwd, 'icons/ui/config.png'), 48))
            # we are loading default config for now...
            if self.config == 'default':
                self.removeConfig.setEnabled(False)
            else:
                self.removeConfig.setEnabled(True)
            self.loadConfig(dev, dev_id, self.config)
            for idx, button in enumerate(self.configButtons.btn_grp.buttons()):
                if button.text() == self.config:
                    self.configButtons.btn_grp.buttons()[idx].setChecked(True)
            self.tablet_data.tablets[dev][dev_id]['config'] = self.config
        else:
            os.mkdir(self.tablet_data.tablets[dev][dev_id]['conf_path'])
            self.configLayout.addButton(
                self.configButtons.addButton("default", 0, 0, 0, os.path.join(self.cwd, 'icons/ui/config.png'), 48))

    def loadConfig(self, dev, dev_id, config):
        # TODO: load cursor configs
        # load pad buttons
        self.config = config
        self.tablet_data.tablets[dev][dev_id]['config'] = self.config
        if not self.toolButtons.buttons[(0, 0)].isHidden():
            self.pad.init_keys(self.tablet_data.tablets[dev][dev_id]['pad']['id'],
                               self.tablet_data.tablets[dev][dev_id]['svg'],
                               self.tablet_data.tablets[dev][dev_id]['pad']['buttons'],
                               self.configs[dev][config]['pad']['buttons'])
        if not self.toolButtons.buttons[(1, 0)].isHidden():
            self.stylus.init_pen(self.tablet_data.tablets[dev][dev_id]['stylus']['id'],
                                 self.configs[dev][config]['stylus'])
            self.stylus.init_eraser(self.tablet_data.tablets[dev][dev_id]['eraser']['id'],
                                 self.configs[dev][config]['eraser'])
            if self.tablet_data.tablets[dev][dev_id]['stylus']['rotate'] == False:
                # turn off rotate, if device doesn't support it
                if 'mapping' in self.configs[dev][config]['stylus']:
                    self.configs[dev][config]['stylus']['mapping']['rotate'] = 'False'
                else:
                    self.configs[dev][config]['stylus']['mapping'] = {'rotate': 'False'}
            self.stylus.mapping.initUI(self.tablet_data.tablets[dev][dev_id]['stylus']['id'],
                                       self.tablet_data.tablets[dev][dev_id]['eraser']['id'],
                                       self.configs[dev][config]['stylus'])
        if not self.toolButtons.buttons[(2, 0)].isHidden():
            self.touch.init(self.tablet_data.tablets[dev][dev_id]['touch']['id'],
                            self.configs[dev][config]['touch'])

    def tabletSelect(self, idx):
        self.updateConfigs()
        self.setToolsAvail(idx)
        self.getConfigs(idx)
        # set first available tool as selected
        if not self.toolButtons.buttons[(0, 0)].isHidden():
            self.toolButtons.buttons[(0, 0)].setChecked(True)
        elif not self.toolButtons.buttons[(1, 0)].isHidden():
            self.toolButtons.buttons[(1, 0)].setChecked(True)
        elif not self.toolButtons.buttons[(2, 0)].isHidden():
            self.toolButtons.buttons[(2, 0)].setChecked(True)
        elif not self.toolButtons.buttons[(3, 0)].isHidden():
            self.toolButtons.buttons[(3, 0)].setChecked(True)

    def toolSelect(self, idx):
        if idx == 0 and not self.toolButtons.buttons[(idx, 0)].isHidden():
            # remove previous layout
            self.pad.show()
            self.stylus.hide()
            self.touch.hide()
        # stylus menu
        elif idx == 1 and not self.toolButtons.buttons[(idx, 0)].isHidden():
            # remove previous layout
            self.pad.hide()
            self.stylus.show()
            self.touch.hide()
        # touch menu
        elif idx == 2 and not self.toolButtons.buttons[(idx, 0)].isHidden():
            # remove previous layout
            self.pad.hide()
            self.stylus.hide()
            self.touch.show()
        # cursor menu
        elif idx == 3 and not self.toolButtons.buttons[(idx, 0)].isHidden():
            # remove previous layout
            self.pad.hide()
            self.stylus.hide()
            self.touch.hide()

    def configSelect(self, idx):
        config = str(self.configButtons.buttons[(idx, 0)].text())
        self.loadConfig(self.dev, self.dev_id, config)
        if config == 'default':
            self.removeConfig.setEnabled(False)
        else:
            self.removeConfig.setEnabled(True)


    def deleteItemsOfLayout(self, layout):
        if layout is not None:
            while layout.count():
                item = layout.takeAt(0)
                widget = item.widget()
                if widget is not None:
                    widget.setParent(None)
                else:
                    self.deleteItemsOfLayout(item.layout())

    def boxdelete(self, box):
        for i in range(self.keys.count()):
            layout_item = self.keys.itemAt(i)
            if layout_item.layout() == box:
                self.deleteItemsOfLayout(layout_item.layout())
                self.vlayout.removeItem(layout_item)
                break

    def updateConfigs(self):
        write = False
        if not self.toolButtons.buttons[(0, 0)].isHidden():
            pad = self.pad.get_config()
            if pad != self.configs[self.dev][self.config]['pad']['buttons']:
                write = True
                self.configs[self.dev][self.config]['pad']['buttons'] = pad
        if not self.toolButtons.buttons[(1, 0)].isHidden():
            stylus = self.stylus.get_config()
            # if stylus['stylus'] != self.configs[self.dev][self.config]['stylus']:
            write = True
            self.configs[self.dev][self.config]['stylus'] = stylus['stylus']
            # if stylus['eraser'] != self.configs[self.dev][self.config]['eraser']:
            write = True
            self.configs[self.dev][self.config]['eraser'] = stylus['eraser']
        if not self.toolButtons.buttons[(2, 0)].isHidden():
            touch = self.touch.get_config()
            if touch != self.configs[self.dev][self.config]['touch']:
                write = True
                self.configs[self.dev][self.config]['touch'] = touch
        # TODO: cursor
        if not self.toolButtons.buttons[(3, 0)].isHidden():
            tmp = 1
        if write:
            reply = None
            if self.toggle is False and self.load is False:
                reply = QMessageBox.question(self, 'Save Config',
                                                   "Write \"%s\" config file?" % self.config,
                                             QMessageBox.Yes, QMessageBox.No)
            # update config if toggle is set or save is called
            if self.toggle or reply == QMessageBox.Yes:
                home = "%s/.wacom-gui" % expanduser("~")
                conf_path = os.path.join(home, self.dev)
                conf_file = os.path.join(conf_path, "%s.json" % self.config)
                if not os.path.exists(conf_path):
                    os.mkdir(conf_path)
                elif os.path.exists(conf_file):
                    os.rename(conf_file, "%s.bak" % conf_file)
                with open(conf_file, 'w') as outfile:
                    json.dump(self.configs[self.dev][self.config], outfile, sort_keys=True,
                              indent=4, separators=(',', ': '))
                if os.path.exists(conf_file):
                    if os.path.exists("%s.bak" % conf_file):
                        os.remove("%s.bak" % conf_file)
        # check if we need to update what config is loaded
        default = {}
        if self.dev is not None:
            for idx, tablet in enumerate(self.tablet_data.tablets[self.dev]):
                if 'config' in tablet.keys():
                    # check if toggle enabled
                    toggle = 0
                    if 'pad' in self.configs[self.dev][tablet['config']]:
                        for button in self.configs[self.dev][tablet['config']]['pad']['buttons'].keys():
                            if self.configs[self.dev][tablet['config']]['pad']['buttons'][button] == 'lhyper z':
                                toggle = 1
                                break
                    default[idx] = {'config': tablet['config'],
                                    'toggle': toggle}
                else:
                    default[idx] = {'config': 'default',
                                    'toggle': 0}
            conf_path = os.path.join("%s/.wacom-gui" % expanduser("~"), self.dev)
            conf_file = os.path.join(conf_path, 'device_default')
            with open(conf_file, 'w') as outfile:
                json.dump(default, outfile, sort_keys=True,
                          indent=4, separators=(',', ': '))

    def quickLoad(self):
        self.load = True
        for idx, button in enumerate(self.tabletButtons.btn_grp.buttons()):
            self.tabletSelect(idx)
        sys.exit()

    def closeEvent(self, event):
        self.updateConfigs()
        event.accept()
        self.deleteLater()
コード例 #17
0
def get_user_profile(username, verbose=False):
    padpy = Pad(verbose=verbose)
    pp(padpy.get_user_profile(username))
コード例 #18
0
def get_user_data(username, verbose=False):
    padpy = Pad(use_monster_api=False, verbose=verbose)
    pp(padpy.get_user_data(username))
コード例 #19
0
def get_user_monsters(username, verbose=False):
    padpy = Pad(use_monster_api=True, verbose=verbose)
    pp(padpy.get_user_monsters(username))
コード例 #20
0
        output = ""
        for obj in self.objects:
            output += obj.toString() + ","
        return output


if __name__ == "__main__":
    # inicjacja modułu pygame
    pygame.init()

    WIDTH = 800
    HEIGHT = 400
    main_window = pygame.display.set_mode((WIDTH, HEIGHT), 0, 32)
    pygame.display.set_caption('Prosty Pong')

    pad1 = Pad(pygame, Color.BLUE, 350, 360)
    pad2 = Pad(pygame, Color.RED, 350, 20)
    ball = Ball(pygame)
    state = GameState([pad1, pad2, ball])

    FPS = 30
    fpsClock = pygame.time.Clock()

    AI_SPEED = 5

    PLAYER_SCORE = '0'
    AI_SCORE = '0'
    fontObj = pygame.font.Font('freesansbold.ttf', 64)

    pygame.key.set_repeat(50, 25)
    x = threading.Thread(target=start_zmq_server, args=(state, ), daemon=True)
コード例 #21
0
ファイル: brickgame.py プロジェクト: snhou/AE402-Pygame
import pygame
from ball import Ball
from pad import Pad
from brick import Brick

pygame.init()
screen = pygame.display.set_mode((600, 400))
pygame.display.set_caption("打磚塊遊戲")
background = pygame.Surface(screen.get_size()).convert()
background.fill((255, 255, 255))
allsprite = pygame.sprite.Group()  #建立全部角色群組
bricks = pygame.sprite.Group()  #建立磚塊角色群組
ball = Ball(10, 300, 200, 30, (255, 0, 0), edge=3)  #建立紅色球物件
allsprite.add(ball)  #加入全部角色群組
pad = Pad()  #建立滑板球物件
allsprite.add(pad)  #加入全部角色群組
clock = pygame.time.Clock()
for row in range(0, 4):  #3列方塊
    for column in range(0, 15):  #每列15磚塊
        if row == 0 or row == 1:  #1,2列為綠色磚塊
            brick = Brick((0, 255, 0), column * 40 + 1, row * 15 + 1)
        if row == 2 or row == 3:  #3,4列為藍色磚塊
            brick = Brick((0, 0, 255), column * 40 + 1, row * 15 + 1)
        bricks.add(brick)  #加入磚塊角色群組
        allsprite.add(brick)  #加入全部角色群組
playing = False  #開始時球不會移動
running = True
while running:
    clock.tick(30)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
コード例 #22
0
ファイル: appmain.py プロジェクト: pointgenesis/Pad
 def test_left_padded_input(self):
     log.debug('100 as a left-padded fixed-length string: %s',
               Pad.left('100', '0', 10))
     log.debug(
         'Courtesy amount ($1,021.65) as a left-padded fixed-length string: %s',
         Pad.left('$1,021.65', ' ', 16))
コード例 #23
0
ファイル: appmain.py プロジェクト: pointgenesis/Pad
    def test_right_padded_input(self):

        log.debug(
            'Legal amount ($1,021.65) as a right-padded fixed-length string: %s',
            Pad.right('One thousand twenty-one dollars and 65 cents', '*', 64))
コード例 #24
0
def main():
    # Init pygame library
    pygame.init()

    # Set window properties
    size = width, height = 800, 600
    screen = pygame.display.set_mode(size)
    pygame.display.set_caption('Pong')

    # Some utils booleans
    ball_launched = False
    game_started = False

    # Load graphics file (background and icon)
    try:
        bg_file = os.path.join(os.path.dirname(__file__), 'graphics',
                               'background.png')
        background = pygame.image.load(bg_file)
        background = background.convert()

        menu_bg_file = os.path.join(os.path.dirname(__file__), 'graphics',
                                    'title.png')
        menu_background = pygame.image.load(menu_bg_file)
        menu_background = menu_background.convert()

        icon_file = os.path.join(os.path.dirname(__file__), 'graphics',
                                 'icon.png')
        icon = pygame.image.load(icon_file)
        pygame.display.set_icon(icon)

    # Catch exceptions
    except pygame.error as e:
        print('Error, graphic file not found: ', filename)
        raise SystemExit(str(e))

    # Define left pad (player one)
    pad_left = Pad((width / 12, height / 4))
    # Define right pad (player two)
    pad_right = Pad((5.5 * width / 6, 3 * height / 4))
    # Define ball
    ball = Ball((width / 2, height / 2))

    # If pygame does not support fonts
    if not pygame.font:
        # Close the game returning this error:
        raise SystemExit('Pygame does not support fonts')

    # Try to load font file
    try:
        filename = os.path.join(os.path.dirname(__file__), 'fonts',
                                'wendy.ttf')
        font = pygame.font.Font(filename, 90)

    # Catch exception
    except pygame.error as e:
        print('Cannot load font: ', filename)
        raise SystemExit(str(e))

    # Define left score (player one points)
    left_score = Score(font, (width / 3, height / 8))
    # Define right score (player two points)
    right_score = Score(font, (2 * width / 3, height / 8))

    # Group all sprites
    sprites = pygame.sprite.Group(pad_left, pad_right, ball, left_score,
                                  right_score)

    # Set the pygame's clock and fps
    clock = pygame.time.Clock()
    fps = 60
    pygame.key.set_repeat(1, 1000 / fps)

    # Set the corners
    top = pygame.Rect(0, 0, width, 5)
    bottom = pygame.Rect(0, height - 5, width, 5)
    left = pygame.Rect(0, 0, 5, height)
    right = pygame.Rect(width - 5, 0, 5, height)

    # infinite Loop
    while 1:
        # Set the fps for clock
        clock.tick(fps)

        # If the game has started
        if game_started == True:

            # Stop movement of both pads
            pad_left.stop()
            pad_right.stop()

            # For each event
            for event in pygame.event.get():
                # If event is equal to QUIT
                if event.type == pygame.QUIT:
                    # Closse the game
                    pygame.quit()
                    return

                # If event is equal to KEYDOWN and the key is W move up player one
                elif event.type == pygame.KEYDOWN and event.key == pygame.K_w:
                    pad_left.move_up()

                # Else if event is equal to KEYDOWN and the key is S move down player one
                elif event.type == pygame.KEYDOWN and event.key == pygame.K_s:
                    pad_left.move_down()

                # Else if event is equal to KEYDOWN and the key is UP Arrow move up player two
                elif event.type == pygame.KEYDOWN and event.key == pygame.K_UP:
                    pad_right.move_up()

                # Else if event is equal to KEYDOWN and the key is DOWN Arrow move down player two
                elif event.type == pygame.KEYDOWN and event.key == pygame.K_DOWN:
                    pad_right.move_down()

                # Else if event is equal to KEYDOWN and the key is SPACE, launch the ball
                elif event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
                    if (ball_launched == False):
                        ball_launched = True
                        ball.start(randint(3, 6), randint(3, 6))

            # if the ball reaches the Y limit point then it reverses its Y axis
            if (ball.rect.colliderect(top) or ball.rect.colliderect(bottom)):
                ball.change_y()

            # else if the ball touches a pad then it reverses its X axis
            elif (ball.rect.colliderect(pad_left.rect)
                  or ball.rect.colliderect(pad_right.rect)):
                ball.change_x()

            # if the ball reaches the left edge X then player two gets a point and the ball restarts its position
            if ball.rect.colliderect(left):
                ball_launched = False
                right_score.score_up()
                ball.reset()
                ball.stop()

            # else if the ball reaches the right edge X then player one gets a point and the ball restarts its position
            elif ball.rect.colliderect(right):
                ball_launched = False
                left_score.score_up()
                ball.reset()
                ball.stop()

            # Update all sprites
            sprites.update()

            # Draw the game background
            screen.blit(background, (0, 0))
            sprites.draw(screen)
            pygame.display.flip()

            # Draw both pads
            screen_rect = screen.get_rect().inflate(0, -10)
            pad_left.rect.clamp_ip(screen_rect)
            pad_right.rect.clamp_ip(screen_rect)

        # Else if the game has not been started
        else:
            # For each event
            for event in pygame.event.get():
                # If event is QUIT then close the game
                if event.type == pygame.QUIT:
                    pygame.quit()
                    return

                # Else if event is KEYDOWN and key is RETURN then Start the game
                elif event.type == pygame.KEYDOWN and event.key == pygame.K_RETURN:
                    game_started = True

            # Render title background
            screen.blit(menu_background, (0, 0))
            pygame.display.flip()
コード例 #25
0
from turtle import Screen
from ball import Ball
from pad import Pad
from time import sleep
from random import randint
from scoreboard import ScoreBoard

screen = Screen()
screen.setup(600, 600)
screen.title("Pong Game")
screen.bgcolor("black")
screen.tracer(0)
end_point=3
# pad init
pad1 = Pad()
pad1.goto(-280, 0)
pad2 = Pad()
pad2.goto(280, 0)
ball = Ball()
scoreboard = ScoreBoard()
# controls
screen.listen()
screen.onkey(pad1.up, "w")
screen.onkey(pad1.down, "s")
screen.onkey(pad2.up, "Up")
screen.onkey(pad2.down, "Down")

# main game while loop
game_is_over = False
while not game_is_over:
    sleep(.01)
コード例 #26
0
 def __init__(self, parent=None):
     super(WacomGui, self).__init__(parent)
     self.setupUi(self)
     self.toggle = False
     self.load = False
     self.cwd = os.path.dirname(os.path.abspath(__file__))
     if self.cwd == '/usr/local/bin':
         self.cwd = '/usr/local/wacom-gui'
     self.setFocusPolicy(Qt.NoFocus)
     # button instances
     self.tabletButtons = ButtonGroup()
     self.toolButtons = ButtonGroup()
     self.configButtons = ButtonGroup()
     # button layouts
     self.tabletLayout = ButtonLayout()
     self.toolLayout = ButtonLayout()
     self.configLayout = ButtonLayout()
     self.tabletScroll.setWidget(self.tabletLayout.frame)
     self.toolScroll.setWidget(self.toolLayout.frame)
     self.configScroll.setWidget(self.configLayout.frame)
     # config files
     self.configs = {}
     # hold current device info
     self.dev = None
     self.dev_id = None
     self.config = None
     # load widgets
     self.pad = Pad()
     self.pad.hide()
     self.stylus = Stylus()
     self.stylus.hide()
     self.touch = Touch()
     self.touch.hide()
     # ui icon
     self.tabletRefresh.setIcon(QIcon(os.path.join(self.cwd, os.path.join(self.cwd, 'icons/ui/refresh.png'))))
     # get connected tablet info
     self.tablet_data = Tablets()
     # attach function to refresh tablets
     self.tabletRefresh.clicked.connect(self.refreshTablets)
     # add buttons for connected tablets
     self.initTabletButtons()
     # generate tool buttons
     self.initToolButtons()
     # add/remove button functions
     self.addConfig.setEnabled(True)
     self.addConfig.clicked.connect(self.newConfig)
     self.removeConfig.clicked.connect(self.verifyConfigRemove)
     # about/help menu
     self.aboutButton.clicked.connect(About.display)
     # refresh tablet list, set tools, configs
     self.refreshTablets()
     self.controlBox.setContentsMargins(0, 0, 0, 0)
     # add control widgets to control box
     hbox = QHBoxLayout()
     hbox.setAlignment(Qt.AlignHCenter)
     hbox.addWidget(self.pad)
     hbox.addWidget(self.stylus)
     hbox.addWidget(self.touch)
     self.controlBox.setLayout(hbox)
     # save config button
     self.saveConfig.clicked.connect(self.updateConfigs)
     # configure device reset button
     self.deviceDefaults.clicked.connect(self.deviceReset)
     # load first tool found
     self.toolSelect(self.toolButtons.btn_grp.checkedId())
     # init button functions
     self.tabletButtons.btn_grp.buttonClicked['int'].connect(self.tabletSelect)
     self.toolButtons.btn_grp.buttonClicked['int'].connect(self.toolSelect)
     self.configButtons.btn_grp.buttonClicked['int'].connect(self.configSelect)
コード例 #27
0
import turtle
import time
from pad import Pad
from ball import Ball
from scoreboard import Scoreboard

screen = turtle.Screen()
screen.bgcolor('black')
screen.setup(width=800, height=600)
screen.title('Pong')
screen.tracer(n=0, delay=0)
r_pad = Pad((350, 0))
l_pad = Pad((-350, 0))

screen.listen()
screen.onkeypress(r_pad.go_up, "Up")
screen.onkeypress(r_pad.go_down, "Down")
screen.onkeypress(l_pad.go_up, "w")
screen.onkeypress(l_pad.go_down, "s")

ball = Ball()
scoreboard = Scoreboard()

game_on = True
while game_on == True:
    time.sleep(0.04)
    screen.update()
    ball.move()

    # detect collision with wall
    if ball.ycor() > 280 or ball.ycor() < -280:
コード例 #28
0
import sys
import time
import module
from pad import Pad
from sequencer import Sequencer
#import main_gui

pad = Pad()
sequencer = Sequencer()


def clear_pressed_key():
    module.pressed_key = (None, None)
    time.sleep(0.1)


def check_pressed_key():
    """
    Get pressed key value from module and to something with it
    """

    # pad_mapping = {
    #     # Pad keys
    #     4:"Kick 1",
    #     3:"Kick 2",
    #     2:"Kick 3",
    #     1:"Kick 4",
    #     8:"Snare 1",
    #     7:"Snare 2",
    #     6:"Snare 3",
    #     5:"Clap 1",
コード例 #29
0
              fg="white",
              bg="#1050b7")
score.place(relx=0.46, rely=0.9)

ball = c.create_oval(w // 2 - 20,
                     h // 2 - 20,
                     w // 2 + 20,
                     h // 2 + 20,
                     fill="#EA9111",
                     outline="#EA9111")
ball_R = (c.coords(ball)[2] - c.coords(ball)[0]) / 2

d = ball_R - (Pad.pad_width * (2 * ball_R - Pad.pad_width))**0.5

# Define pads
left_pad = Pad(0, 0, c)
right_pad = Pad(w - Pad.pad_width, 0, c)

# V for balls
vx, vy = random.choice([-5, 5]), random.choice([6, -6])


def keypress(event):
    key = event.keysym

    if key.lower() == "w":
        left_pad.active = True
        left_pad.speed = -10

    if key.lower() == "s":
        left_pad.active = True
コード例 #30
0
ファイル: connection.py プロジェクト: zosiakropka/academia
class PadTCPConnection(dispatcher_with_send):

    CHNL = "TCPConnection"

    def __init__(self, *args, **kwargs):
        logging.info("%s client" % (self.CHNL))

        self.buffer = ""
        self.pad_server = kwargs.pop('pad_server')
        self.pad_id = None
        self.pad = None
        self.conn_id = None

        sock = kwargs['sock'] if 'sock' in kwargs else args[0]
        dispatcher_with_send.__init__(self, *args, **kwargs)
        sock.setblocking(0)

    def handle_read(self):
        """
        Low-level receiving messages. Calls handle_message() on each complete
        message record.
        """
        data = None
        try:
            data = self.recv(CHUNK_SIZE)
        except:
            pass
        if data:
            self.buffer += data
            if DELIMITER in self.buffer:
                records = self.buffer.split(DELIMITER)
                self.buffer = records.pop()
                for record in records:
                    self.handle_message(record)

    def handle_message(self, record):
        """
        Try to decode messge record and process it adequately. Should be
        called by handle_read() when receiving single record is complete.
        """
        data = decode(record)
        if data and "purpose" in data:
            logging.debug("%s has data onboard, purpose: %s" % (self.CHNL, data["purpose"]))
            purpose = data["purpose"]
            if purpose == "pad" and "message" in data:
                self.pad_id = data.pop("message")
                self.pad = Pad(self.pad_id)
            elif purpose == "patches" and "message" in data and self.pad_id:
                try:
                    token = data.pop("token", None)
                    tokens.validate(
                        token,
                        scope.access_obj(Note.objects.get(pk=self.pad_id), "edit"),
                    )
                    data["message"] = self.pad.process(data["message"])

                    self.pad_broadcast(data)
                except Exception:
                    response = {
                        "purpose": "auth",
                        "message": "fail"
                    }
                    self.send_record(response)

    def pad_broadcast(self, data):
        """
        Broadcast message within current pad.
        """
        self.pad_server.pad_broadcast(encode(data), self.pad_id, self.conn_id)

    def send_record(self, record):
        dispatcher_with_send.send(self, "%s%s%s" % (record, DELIMITER, '\n'))
コード例 #31
0
ファイル: user.py プロジェクト: vbraun/sagepad
 def get_all_pads(self, limit=25):
     return list(Pad.iterate(self, limit))
コード例 #32
0
def get_monster(monster_id, verbose=False):
    """ outputs a monster's complete stats """
    padpy = Pad(verbose=verbose)

    monster = padpy.get_monster(monster_id)
    padpy.pretty_print(monster)