Ejemplo n.º 1
0
 async def bsevents(self, ctx):
     await ctx.trigger_typing()
     events = await self.client.get_events()
     current_events = events.current
     next_events = events.upcoming
     em1 = discord.Embed(title=f"Current Events", color=ctx.author.color)
     desc = ""
     for e in current_events:
         e = box.Box(e)
         desc += f"{self.get_event_emoji(e.gameMode)}{e.slotName}: **{e.gameMode}**\n{e.mapName}\n{self.bot.get_emoji(650865620094681108)} **Ends in:** {self.fmt_time(e.endTimeInSeconds)}"
         if e.hasModifier:
             desc += f" (Modifier: {e.modifierName})"
         desc += "\n\n"
     em1.description = desc
     desc = ""
     em2 = discord.Embed(title="Upcoming Events", color=ctx.author.color)
     for e in next_events:
         e = box.Box(e)
         desc += f"{self.get_event_emoji(e.gameMode)}{e.slotName}: **{e.gameMode}**\n{e.mapName}\n{self.bot.get_emoji(650865620094681108)} **Starts in:** {self.fmt_time(e.startTimeInSeconds)}"
         if e.hasModifier:
             desc += f" (Modifier: **{e.modifierName}**)"
         desc += "\n\n"
     em2.description = desc
     em2.set_footer(text=str(ctx.author), icon_url=str(ctx.author.avatar_url))
     await ctx.send(embed=em1, edit=False)
     await ctx.send(embed=em2, edit=False)
Ejemplo n.º 2
0
    def __init__(self, parent):
        #offsets not accounted for at present in drawing.
        self.xOffset = 0
        self.yOffset = 0

        self.width = parent.width
        self.height = 15
        self.closeBoxWidth = 10
        self.title = parent.id

        self.dead = False

        self.parent = parent

        self.font = data.fonts['system']
        self.mainColor = data.colors['light grey']
        self.closeColor = data.colors['red']

        box.Box.__init__(self, self.xOffset, self.yOffset, self.width,
                         self.height)

        self.closeBoxOffset = self.width - self.closeBoxWidth

        #header contents
        self.subboxes = {}
        self.subboxes['main'] = box.Box(self.xOffset, self.yOffset,
                                        self.closeBoxOffset, self.height)
        self.subboxes['close'] = box.Box(self.xOffset + self.closeBoxOffset,
                                         self.yOffset, self.closeBoxWidth,
                                         self.height)
Ejemplo n.º 3
0
    def __init__(self, screen, infoNode, poke):
        """
      aa

      screen - the screen to blit to.
      infoNode - the <info> node from the menu XML file.
      poke - the pokemon.
      """

        self.screen = screen

        fFont = font.Font(
            os.path.join(settings.path, "data",
                         data.getAttr(infoNode, "font", data.D_STRING)))

        size = ((self.screen.get_width() / 2) - (OBJECTBUFFER * 2),
                (self.screen.get_height() / 2) - (OBJECTBUFFER * 2))
        fn = os.path.join(settings.path, "data",
                          data.getAttr(infoNode, "box", data.D_STRING))
        self.infoBox = box.Box(size, fn).convert(self.screen)

        info = {
            "No.": data.getAttr(poke.speciesNode, "dex", data.D_STRING),
            "Name": poke.getName(),
            "Type": "TODO",
            "OT": str(poke.trainer),
            "ID No.": str(poke.trainerID),
            "Item": str(poke.heldItem)
        }
        order = ["No.", "Name", "Type", "OT", "ID No.", "Item"]

        pointerY = BORDER
        for inf in order:
            fFont.writeText(inf, self.infoBox, (BORDER, pointerY))
            text = info[inf]
            fFont.writeText(
                text, self.infoBox,
                (size[0] - fFont.calcWidth(text) - BORDER, pointerY))
            pointerY += fFont.height + LINEBUFFER

        self.infoBoxLocation = (self.screen.get_width() - size[0] -
                                OBJECTBUFFER, OBJECTBUFFER)

        size = (self.screen.get_width() - (OBJECTBUFFER * 2),
                (self.screen.get_height() / 2) - (OBJECTBUFFER * 2))
        self.memoBox = box.Box(size, fn).convert(self.screen)

        pointerY = BORDER
        fFont.writeText("%s nature." % "TODO", self.memoBox,
                        (BORDER, pointerY))
        pointerY += fFont.height + LINEBUFFER
        fFont.writeText("Met in %s." % "TODO", self.memoBox,
                        (BORDER, pointerY))

        self.memoBoxLocation = (OBJECTBUFFER, self.screen.get_height() -
                                size[1] - OBJECTBUFFER)
Ejemplo n.º 4
0
 async def meme(self, ctx):
     """Gives a random meme."""
     lang = ctx.lang.current
     if lang == "it":
         subreddit = "r/memesITA"
     else:
         subreddit = choice(["r/memes", "r/dankmemes"])
     r = await self.bot.session.get(
         f"https://www.reddit.com/{subreddit}/top.json?sort=top&t=day&limit=500"
     )
     r = await r.json()
     r = box.Box(r)
     data = choice(r.data.children).data
     img = data.url
     title = data.title
     upvotes = data.ups
     downvotes = data.downs
     em = discord.Embed(
         color=ctx.author.color,
         title=title,
         url=f"https://reddit.com{data.permalink}",
     )
     em.set_image(url=img)
     em.set_author(name=ctx.author.name, icon_url=ctx.author.avatar_url)
     em.set_footer(text=f"👍{upvotes} | 👎 {downvotes}")
     await ctx.send(embed=em)
Ejemplo n.º 5
0
    def listen(self):
        print "Connected to C&C Template Server. Waiting for instructions..."

        try:
            while True:
                # Keeps running receiving data. Once received
                # it its automatically un-serialized and converted
                # into an Python dictionary object.
                serialized_data = pickle.loads(
                    self._clientsocket.recv(self.BUFFER_SIZE))
                template_data = box.Box(serialized_data)

                # TemplateManager decomposes serialized data
                # and take actions to execute the selected program
                TemplateManager(template_data)

                print "Sending back to C&C => OK status"
                self.send('ok')

        except socket.error as e:
            print "Server disconnection: {}".format(e)
            self.reconnect()

        except EOFError as e:
            print "Server disconnection...".format(e)
            self.reconnect()

        else:
            # If template data was received correctly, then acknowledge.
            self.send('skip')
Ejemplo n.º 6
0
 async def error(self, ctx, code):
     """Gets info on an error by code."""
     if not self.dev_check(ctx.author.id):
         return await ctx.send(
             f"Sorry, but you can't run this command because you ain't a developer! {self.bot.get_emoji(691757044361068574)}"
         )
     data = await self.bot.db.errors.find_one({"code": code})
     if not data:
         return await ctx.send(
             "No error with that code was found. Check it!")
     data = box.Box(data)
     if len(data.error) < 2000:
         err = data.error
     else:
         resp = await self.session.post("https://hastebin.com/documents",
                                        data=data.error)
         resp = await resp.json()
         err = f"**The error message is too long to fit! The error has been uploaded to Hastebin:\n\nhttps://hastebin.com/{resp['key']}"
     guild = self.bot.get_guild(data.guild)
     em = discord.Embed(color=ctx.author.color, title="Error Information")
     em.description = f"**Traceback**\n\n```\n{err}```"
     em.add_field(name="Code", value=f"**{code}**", inline=True)
     em.add_field(name="Server", value=guild)
     em.add_field(name="Channel",
                  value=f"#{data.channel}\n(Invite: {data.invite})")
     em.add_field(name="User", value=data.user)
     em.add_field(name="Command Content", value=data.content)
     await ctx.send(embed=em)
Ejemplo n.º 7
0
def benchmark(function, *args):
    '''
    Calculate the time to execute the function.

    Parameters
    ----------
    arg0 : function
        Function to be tested
    arg1 : object
        Arguments that will be applied in the function

    Returns
    -------
    None

    Example
    -------
    >>> benchmark_find(function, [12,85,5,1,98,54,32,8], 5)
    '''
    start = time.clock()
    indice = function(*args)
    stop = time.clock()

    caixa = b.Box()
    caixa.add_text_line(function.__name__)
    caixa.add_text_line('Return: ' + str(indice))
    caixa.add_text_line('Execution Time: ' + str(stop - start))
    caixa.print_box()
Ejemplo n.º 8
0
    def load_tool_config_file(self,
                              tool_name,
                              arch,
                              version,
                              target_file=None):
        """ Loads the tool config file: (JSON data -> BOX object) conversion"""
        try:
            # print(f"Loading Template ({tool_name}) Arch: {arch} Version: ({version})")
            self.__locate_tool_config_file(tool_name, arch, version)
            cfg_file = f"{self.tool_directory}/{self.version}/{self.tool_name}.json"
            self.logger.log('Config file path: {}'.format(cfg_file))
            j = open(cfg_file, 'r')
        except FileNotFoundError as e:
            self.logger.log('Cannot open config JSON file: {}'.format(e),
                            level='DEBUG')

        else:
            self.logger.log('Loading JSON config file', level='DEBUG')
            try:
                json_data = json.load(j)

                # This will set the dictionary required to hold
                # custom user variables used in json template/config files.
                json_data['configuration']['execution'][
                    'download_sample'] = False
                json_data['configuration']['execution'][
                    'custom_user_vars'] = {}
                json_data['configuration']['execution']['delay'] = 0
                json_data['actions']['action'] = ""

            except json.JSONDecodeError:
                self.logger.log('Error during JSON decoding', level='DEBUG')
                return False
            else:
                j.close()
                self.logger.log('The JSON config file was loaded correctly',
                                level='DEBUG')

                # The Config JSON data is loaded and then converted
                # into an extended python dict by using the python-box
                # module. Through this way, attributes can be accessed
                # with dot notation:
                #
                #   self.automation.normal_scan.execute = True
                #

                self.__dict__.update(box.Box(json_data))

                #print("JSON_AND_DICT_DATA: {}".format(self.__dict__))

            if target_file is None:
                self.logger.log('>> Target file is not set', level='DEBUG')
                self.configuration.execution.download_sample = False

            elif target_file is not None:
                self.logger.log('>> Target file is set', level='DEBUG')
                self.configuration.execution.download_sample = True
                self.download_url = target_file.download_url
            else:
                self.logger.log('>> Unknown target', level='DEBUG')
Ejemplo n.º 9
0
def main():
    WINSIZE = 640, 480
    pygame.init()
    #screen = pygame.display.set_mode(WINSIZE,0,8)
    #pygame.display.set_caption('Move the Box!')

    NUMBER_OF_STARS = 250
    STARTING_ANGLE = 180
    CLOSEST_STAR_COLOR = (255, 255, 255)
    STAR_SIZE_IN_PIXELS = 2

    # A few preset speeds for the user to see.

    preset_speeds = ((10, 1), (20, 2), (40, 4), (60, 6), (80, 8))
    current_speed = 2

    # For fullscreen, replace pygame.SWSURFACE with pygame.FULLSCREEN

    display = pygame.display.set_mode((640, 480), pygame.SWSURFACE)

    my_starfield = Starfield(display, display.get_rect(), NUMBER_OF_STARS,
                             STARTING_ANGLE, preset_speeds[current_speed],
                             STAR_SIZE_IN_PIXELS, CLOSEST_STAR_COLOR)

    #screen.fill(THECOLORS["black"])

    box1 = box.Box(display, (32, 32), (1, 1), THECOLORS["black"],
                   THECOLORS["white"])

    done = False
    while not done:
        my_starfield.update()
        box1.draw()
        pygame.display.update()
        events = pygame.event.get()
        for e in events:
            if (e.type == QUIT):
                done = True
                break
            elif (e.type == KEYDOWN):
                dx, dy = 0, 0

                if (e.key == K_ESCAPE):
                    done = True
                    break
                if (e.key == K_f):
                    pygame.display.toggle_fullscreen()
                if (e.key == K_DOWN):
                    dy += 1
                if (e.key == K_UP):
                    dy -= 1
                if (e.key == K_RIGHT):
                    dx += 1
                if (e.key == K_LEFT):
                    dx -= 1

                box1.chV(dx, dy)
    print "Exiting!"

    return
Ejemplo n.º 10
0
 def post(self):
     if request.is_json:
         userData = box.Box(request.get_json())
         if not userData.username or not userData.password:
             res = {
                 "status_code": 200,
                 "message": "Missing Username/Password field!"
             }
             return jsonify(res)
         else:
             hashed_pw = bcrypt.hashpw(userData.password.encode('utf8'),
                                       bcrypt.gensalt())
             registeredUsers.insert_one({
                 "username": userData.username,
                 "password": hashed_pw,
                 "tokens": 10,
                 "sentence": ""
             })
             res = {
                 "status_code": 200,
                 "message": "You are now registered at our API.",
                 "tokens": 10
             }
             return jsonify(res)
     else:
         res = {
             "status_code": 300,
             "message": "Please send data in json format."
         }
         return jsonify(res)
Ejemplo n.º 11
0
    def __init__(self,
                 population_size,
                 elitism=True,
                 elitismFraction=0.10,
                 deathFraction=0.10,
                 mutationProb=0.001):

        self.population_size = population_size
        self.elitism = elitism
        self.mutationProb = mutationProb
        self.elistismFraction = elitismFraction
        self.infantMortality = deathFraction

        file = open("boxes.txt")
        fileinput = file.readlines()
        file.close()

        rawboxes = []
        for index in range(len(fileinput)):
            rawboxes.append(fileinput[index].replace("\n", "").split("\t"))
            for index2 in range(len(rawboxes[index])):
                rawboxes[index][index2] = int(rawboxes[index][index2])

        objectBoxes = []
        for item in rawboxes:
            placing_box = box.Box(item[0], item[1], item[2], item[3], item[4])
            objectBoxes.append(placing_box)

        self.population = []
        for iteration in range(self.population_size):
            self.population.append(individual.Individual(
                "random", objectBoxes))
Ejemplo n.º 12
0
   def __init__(self, text, font, screen, scriptEngine, choices):
      """
      Initialize the dialog and create the choice box.

      text - a list of lines of text to go in the dialog.
      font - the font with which to write the text.
      screen - the surface to draw the dialog onto.
      scriptEngine - the engine to return the option chosen to.
      choices - the possible options to choose from.
      """

      #initialize the dialog
      Dialog.__init__(self, text, font, screen, False) #initialize the main dialog

      #store variables we'll need again
      self.scriptEngine = scriptEngine
      self.choices = choices

      #create the choice box and write the options onto it
      maxWidth = max(map(self.font.calcWidth, self.choices))
      size = (maxWidth+(BORDER*2)+self.sideCursor.get_width(),
              ((self.font.height+LINEBUFFER)*len(self.choices))-LINEBUFFER+(BORDER*2))
      self.choiceBox = box.Box(size).convert(self.screen)

      for i in range(0, len(choices)):
         choice = choices[i]
         location = BORDER+self.sideCursor.get_width(), BORDER+(i*(self.font.height+LINEBUFFER))
         self.font.writeText(choice, self.choiceBox, location)

      #calculate the location of the choice box
      self.choiceLocation = (self.screen.get_width()-self.choiceBox.get_width()-OBJECTBUFFER,
                             self.location[1]-self.choiceBox.get_height()-OBJECTBUFFER)

      #set the current selected option to the first one
      self.current = 0
Ejemplo n.º 13
0
    def parse_cbs_station_data(self, data):
        """ Adds songs to list for cbs stations """

        for each_data in data:
            box_data = box.Box(each_data)
            for each_song in box_data.data.recentEvents:
                self.music_list.append([each_song.artist, each_song.title])
Ejemplo n.º 14
0
def init():
    global player,boxs
    player = boy.Boy()
    for i in range(2):
        for j in range(8):
            temp = box.Box( i*95,  j * 95)
            boxs.append(temp)
Ejemplo n.º 15
0
def _get_reporting_variables(config, section):
    var_dict = {}
    for option in allowed_reporting_options:
        var_names = get_variable_names_for_reporting(
            config, section, option
        )
        var_dict[option] = var_names
    return box.Box(var_dict, frozen_box=True)
Ejemplo n.º 16
0
 def __init__(self):
     self.table = []
     for x in range(3):
         row = []
         for y in range(3):
             square = box.Box(x, y)
             row.append(square)
         self.table.append(row)
Ejemplo n.º 17
0
    def start(self, current_state_name, persistent, surface):
        super().start(current_state_name, persistent, surface)

        self.minefield = minefield.Minefield(self.persist["width"],
                                             self.persist["height"],
                                             self.persist["number_of_mines"])
        self.minefield.pos = (20 + prepare.box_tiles["width"],
                              20 + prepare.box_tiles["height"])
        self.minefield_rect = self.minefield.surface.get_rect(
            topleft=self.minefield.pos)

        border = box.Box(
            (self.minefield_rect.width + 2 * prepare.box_tiles["width"],
             self.minefield_rect.height + 2 * prepare.box_tiles["height"]),
            (self.minefield_rect.topleft[0] - prepare.box_tiles["width"],
             self.minefield_rect.topleft[1] - prepare.box_tiles["height"]))
        border.draw(surface)

        mines_remaining = "{} mine{} remaining".format(
            self.minefield.mines_remaining,
            "s" if self.minefield.mines_remaining != 1 else "")
        textbox_size = (220, 35)
        self.textbox = box.Box(textbox_size, (self.window_size[0] -
                                              (20 + textbox_size[0]), 20),
                               text=mines_remaining)

        self.buttons = {
            button.Button(
                (self.window_size[0] -
                 (20 + prepare.BUTTON_SIZE[0]), textbox_size[1] + 40),
                "NEW",
                centerx=False),
            button.Button(
                (self.window_size[0] -
                 (20 + prepare.BUTTON_SIZE[0]), textbox_size[1] + 90),
                "MENU",
                centerx=False),
            button.Button(
                (self.window_size[0] -
                 (20 + prepare.BUTTON_SIZE[0]), textbox_size[1] + 140),
                "QUIT",
                centerx=False)
        }

        self.win_lose_announced = False
Ejemplo n.º 18
0
def _get_summary_variables(config,  section):
    var_dict = {}
    for option in allowed_reporting_options:
        sum_var_names = get_variable_names_for_reporting(
            config, section, option + '_summary'
        )
        if len(sum_var_names) > 0:
            var_dict[option] = sum_var_names
    return box.Box(var_dict, frozen_box=True)
Ejemplo n.º 19
0
def validUser(username, password):
    foundUser = box.Box(registeredUsers.find_one({"username": username}))
    if foundUser:
        if bcrypt.checkpw(password.encode('utf8'), foundUser.password):
            return True
        else:
            return False
    else:
        return False
Ejemplo n.º 20
0
def spacing_bar(TotalBox, screen, size, position, BackgroundColor, BoxColor):
    x = position[0]
    # horizontal bars
    count = 1
    while count <= TotalBox:
        x = x + size[0] * 5
        count = count + 1
        boxA = box.Box(screen, size, (x, position[1]), BackgroundColor,
                       BoxColor)
        boxA.draw()
Ejemplo n.º 21
0
def compile_steps(config: box.Box) -> box.Box:
    validate_config(config)
    branch = get_git_branch()
    projects = get_affected_projects(branch, config)
    can_autodeploy = check_autodeploy(config.deploy.to_dict())
    scope_fn = dict(project=generate_project_steps, stair=generate_stair_steps)

    steps = []
    previous_stair = box.Box({'continue_on_failure': False})
    for stair in iter_stairs(config.stairs, can_autodeploy):
        stair_projects = list(iter_stair_projects(stair, projects))
        if stair_projects:
            steps += generate_wait_step(previous_stair)
            steps += generate_block_step(config.block.to_dict(), stair,
                                         stair_projects)
            steps += scope_fn[stair.scope](stair, stair_projects)
        previous_stair = stair

    return box.Box({'steps': steps})
Ejemplo n.º 22
0
   def __init__(self, text, screen, drawCursor=True):
      """
      Create the dialog box and load cursors.

      text - a list of lines of text to go in the dialog.
      font - the font with which to write the text.
      screen - the surface to draw the dialog onto.
      soundManager - the sound manager.
      drawCursor - whether a continuation cursor should be drawn when the text has finished writing.
      """

      #store variables we'll need again
      self.text = text.split(LINESEP)
      self.screen = screen
      self.drawCursor = drawCursor
      
      #determine the speed to write at, in characters per tick
      if settings.textSpeed == "SLOW":
         self.speed = 1
      elif settings.textSpeed == "MEDIUM":
         self.speed = 2
      elif settings.textSpeed == "FAST":
         self.speed = 4

      #parse the dialog xml file
      fn = os.path.join(settings.path, "data", globs.DIALOG)
      root = data.getTreeRoot(fn, "Ditto main")
      transparency = data.getAttr(root, "transparency", data.D_INT3LIST)

      #create font
      fontPath = os.path.join(settings.path, "data", globs.FONT)
      self.font = font.Font(fontPath)

      #create the box
      size = ((self.screen.get_width()-(OBJECTBUFFER*2), (len(self.text)*(self.font.height+LINEBUFFER))-LINEBUFFER+(BORDER*2)))
      self.box = box.Box(size).convert(self.screen)

      #load the cursors
      cursorPath = os.path.join(settings.path, "data", data.getAttr(root, "cursor", data.D_STRING))
      self.cursor = data.getImage(cursorPath).convert(self.screen)
      self.cursor.set_colorkey(transparency)
      self.cursorLocation = (self.screen.get_width()-OBJECTBUFFER-BORDER-self.cursor.get_width(),
                             self.screen.get_height()-OBJECTBUFFER-BORDER-self.cursor.get_height())

      cursorPath = os.path.join(settings.path, "data", data.getAttr(root, "sidecursor", data.D_STRING))
      self.sideCursor = data.getImage(cursorPath).convert(self.screen)
      self.sideCursor.set_colorkey(transparency)

      #calculate location of dialog box
      self.location = OBJECTBUFFER, self.screen.get_height()-self.box.get_height()-OBJECTBUFFER

      #start progress at 0 and set drawing and busy
      self.progress = 0
      self.writing = True
      self.busy = True
Ejemplo n.º 23
0
    def post(self):
        if request.is_json:
            userData = box.Box(request.get_json())
            if not userData.username or not userData.password:
                res = {
                    "status_code": 200,
                    "message": "Missing Username/Password field!"
                }
                return jsonify(res)

            if validUser(userData.username, userData.password):
                tokens = getToken(userData.username)
                if tokens > 0:
                    foundUser = box.Box(registeredUsers.find_one({
                        "username": userData.username}))
                    if foundUser:
                        tokens -= 1
                        setTokens(foundUser.username, tokens)
                        res = {
                            "status_code": 200,
                            "sentence": foundUser.sentence,
                            "tokens": foundUser.tokens
                        }
                        return jsonify(res)
                else:
                    res = {
                        "status_code": 302,
                        "message": "Not enough tokens!"
                    }
                    return jsonify(res)
            else:
                res = {
                    "status_code": 404,
                    "message": "User does'nt exist in our databases."
                }
                return jsonify(res)
        else:
            res = {
                "status_code": 300,
                "message": "Please send data in json format."
            }
            return jsonify(res)
Ejemplo n.º 24
0
def load_state(file):
    with open(file) as f:
        orig = json.load(f)['params']
    ret = box.Box()
    for k, v in orig.items():
        ks = k.split('.')
        parent = ret
        for k_seg in ks[:-1]:
            parent = parent.setdefault(k_seg, {})
        parent[ks[-1]] = v
    return ret
Ejemplo n.º 25
0
def test_verify_token():
    def test_func(*args, **kwargs):
        return args, kwargs

    verify_token_func = utils.verify_token(test_func)
    request = {"data": {"token": settings.SLACK_VERIFICATION_TOKEN}}
    request = box.Box(request)
    data = verify_token_func(request)
    assert isinstance(data, tuple), "Should have called the wrapped function"

    request.data.token = "test"
    data = verify_token_func(request)
    assert isinstance(data, Response), "Should have returned error Response"

    request = {
        "data": {"payload": json.dumps({"token": settings.SLACK_VERIFICATION_TOKEN})}
    }
    request = box.Box(request)
    data = verify_token_func(request)
    assert isinstance(data, tuple), "Should have called the wrapped function"
Ejemplo n.º 26
0
 def get(self, key):
     fallback = box.Box(dict(zip(self._columns(), (key, *self.defaults))))
     try:
         obj = self[key]
         logger.debug(f"DatabaseTable.get | getting {key}: {obj}")
         return obj
     except KeyError:
         logger.debug(
             f"DatabaseTable.get | getting {key}: {fallback}; key does not exist"
         )
         return fallback
Ejemplo n.º 27
0
def main():
    WINSIZE = 640, 480
    pygame.init()
    screen = pygame.display.set_mode(WINSIZE, 0, 8)
    pygame.display.set_caption('Prova di TdPII!')

    screen.fill(THECOLORS["black"])

    box1 = box.Box(screen, (32, 32), (1, 1), THECOLORS["black"],
                   THECOLORS["white"])
    box2 = box.Box(screen, (32, 32), (-1, -1), THECOLORS["black"],
                   THECOLORS["red"])
    box3 = box.Box(screen, (32, 32), (1, 4), THECOLORS["black"],
                   THECOLORS["green"])

    # The Main Event Loop
    done = False
    while not done:
        # Drawing:
        box1.draw()
        box2.draw()
        box3.draw()
        # Drawing finished this iteration?  Update the screen
        pygame.display.update()

        # Event Handling:
        events = pygame.event.get()
        for e in events:
            if (e.type == QUIT):
                done = True
                break
            elif (e.type == KEYDOWN):
                if (e.key == K_ESCAPE):
                    done = True
                    break
                if (e.key == K_f):
                    pygame.display.toggle_fullscreen()

    print "Exiting!"

    return
Ejemplo n.º 28
0
    def parse_tunegenie_data(self, data):
        """ Adds songs to list for tunegenie stations"""

        for each in data:
            mbox = box.Box(each)
            for eachlist in mbox.response:
                if eachlist.artist.startswith(
                        'Weekdays,') or eachlist.artist.startswith(
                            "The Valley's") or eachlist.artist.startswith(
                                "Sundays,"):
                    continue
                self.music_list.append([eachlist.artist, eachlist.song])
Ejemplo n.º 29
0
def init():
    global player,boxs, cand
    player = boy.Boy()
    cand = candy(1,2)

    color = 0
    for i in range(8):
        for j in range(16):
            if i == 0: color = 1
            if i == 1: color = 2
            temp = box.Box( ((j*1.099999)*95-570)  ,  (i*1.099999) * 95-570,color)
            boxs.append(temp)
Ejemplo n.º 30
0
 def __init__(self):
     super().__init__()
     self.buttons = (button.Button((self.window_size[0] // 2, 180),
                                   "PLAY",
                                   size=prepare.BIG_BUTTON_SIZE),
                     button.Button((self.window_size[0] // 2, 245), "BACK"))
     self.play_button = self.buttons[0]
     self.top_textbox_text = "Customize your Minefield"
     self.top_textbox = box.Box((280, 35), (self.window_size[0] // 2, 20),
                                self.top_textbox_text,
                                centerx=True)
     self.inputtexts = {
         "width": "width",
         "height": "height",
         "mines": "mines"
     }
     self.inputboxes = {
         "width":
         box.Box((80, 35), (self.window_size[0] * 1 / 5, 110),
                 self.inputtexts["width"],
                 tiles=prepare.textbox_tiles,
                 centerx=True,
                 name="width"),
         "height":
         box.Box((80, 35), (self.window_size[0] / 2, 110),
                 self.inputtexts["height"],
                 tiles=prepare.textbox_tiles,
                 centerx=True,
                 name="height"),
         "mines":
         box.Box((80, 35), (self.window_size[0] * 4 / 5, 110),
                 self.inputtexts["mines"],
                 tiles=prepare.textbox_tiles,
                 centerx=True,
                 name="mines")
     }
     self.valid_chars = "0123456789"
     self.active_inputbox = None
     self.textcursor = "|"
     self.max_sidelength = 40