Пример #1
0
 def update(self):
   
   #Return selection value chosen
   if events.get("ACTION",0):
     return self.selectedText[self.selection][2]
   
   #Control selection with up/down keys
   if events.get("UP",0): self.selection -= 1
   if events.get("DOWN",0): self.selection += 1
   if self.selection < 0: self.selection = 0
   if self.selection > len(self.selectText) - 1: self.selection = len(self.selectText) - 1
   
   return 0
Пример #2
0
    def update(self):

        #Return selection value chosen
        if events.get("ACTION", 0):
            return self.selectedText[self.selection][2]

        #Control selection with up/down keys
        if events.get("UP", 0): self.selection -= 1
        if events.get("DOWN", 0): self.selection += 1
        if self.selection < 0: self.selection = 0
        if self.selection > len(self.selectText) - 1:
            self.selection = len(self.selectText) - 1

        return 0
Пример #3
0
    def run(self):
        curr_command = ''
        self.print_commands(curr_command)
        while True:
            try:
                ev = events.get()
            except Exception:
                continue

            if ev.event_type != events.EVENT_KEY_DOWN:
                continue

            k = ev.key_code
            c = chr(k & 0xff)
            if k == keys.KEY_ESC:
                curr_command = ''
                break
            if k == keys.KEY_ENTER:
                break
            elif k == keys.KEY_BACKSPACE:
                curr_command = curr_command[:-1]
            elif ev.char:
                curr_command += ev.char
            self.print_commands(curr_command)

        cmd = curr_command.split(' ', 1)
        if len(cmd) == 1:
            return cmd[0], None
        return cmd[0], cmd[1]
Пример #4
0
    def textbox(self, y, x, width, value="", edit=False):
        # Draw a textbox and return the exit key
        value = str(value)
        cursor = '_' if edit else ''

        attr = keys.A_BOLD if edit else None
        self.addstr(
            y, x, '[{value: <{width}}]'.format(value=value + cursor,
                                               width=width), attr)
        self.refresh()
        k = None
        while edit:
            try:
                ev = events.get()
            except Exception:
                continue

            if ev.event_type not in KEY_EVENTS:
                return 0, ev

            if ev.event_type == events.EVENT_KEY_UP:
                continue

            k = ev.key_code
            if k in EXIT_FIELD_KEYS:
                edit = False
            elif k in [keys.KEY_LEFT, keys.KEY_RIGHT]:
                if value.isdigit():
                    diff = -1 if k == keys.KEY_LEFT else 1
                    value = int(value)
                    value += diff
                    value = str(value)
                    edit = False
            elif k == keys.KEY_BACKSPACE:
                value = value[:-1]
            elif ev.char and len(value) < width:
                value += ev.char

            self.addstr(
                y, x, '[{value: <{width}}]'.format(value=value + '_',
                                                   width=width), attr)
            self.refresh()

        return k, value
Пример #5
0
    def listbox(self, y, x, width, value="", options=None, edit=False):
        # Draw a textbox and return the exit key
        value = str(value)
        options = ['Undefined'] if options is None else options

        attr = keys.A_BOLD if edit else None
        self.addstr(
            y, x, '[< {value: <{width}} >]'.format(value=value,
                                                   width=width - 4), attr)
        self.refresh()
        k = None
        while edit:
            try:
                ev = events.get()
            except Exception:
                continue

            if ev.event_type != events.EVENT_KEY_DOWN:
                continue

            k = ev.key_code
            if k in EXIT_FIELD_KEYS:
                edit = False
            elif k in [keys.KEY_LEFT, keys.KEY_RIGHT]:
                if value in options:
                    pos = options.index(value)
                    change = -1 if k == keys.KEY_LEFT else 1
                    pos = (pos + change) % len(options)
                else:
                    pos = 0
                value = options[pos]
                edit = False

            self.addstr(
                y, x, '[< {value: <{width}} >]'.format(value=value,
                                                       width=width - 4), attr)
            self.refresh()

        return k, value
Пример #6
0
 def update(self):
   if events.get("CANCEL", 0): return 1
   else: return Menu.update(self)
Пример #7
0
def process_cmd(nick, msg):    
    """Splits the message, processes the
    commands and does all the relevant
    functions required.
    
    Should reverse the 'rank' if 
    statements but it's not much of
    a problem.
    """
    cmd = msg.split(" ")
    rank = v.getrank(nick)
    if len(cmd) == 1:
        log("*" + cmd[0].capitalize() + "* | nick: " + nick, m_type="COMMAND", colour=Fore.CYAN)
        #ACTION_LOG.info(Fore.MAGENTA + "COMMAND " + Fore.RESET + " " + cmd[0] + " | nick: " + nick)
    else:
        log("*" + cmd[0].capitalize() + "* | args: " + " ".join(cmd[1:]) + " | nick: " + nick, m_type="COMMAND", colour=Fore.CYAN)
        #ACTION_LOG.info(Fore.MAGENTA + "COMMAND " + Fore.RESET + " " + cmd[0] + " | args: " + " ".join(cmd[1:]) + " | nick: " + nick)
    
    try:
        # regular user
        # rank = 1
        if rank >= 1:
            #! emotes !#
            if cmd[0] == "fliptable": c.say("(╯°□°)╯︵ ┻━┻")
            elif cmd[0] == "puttableback": c.say("┬─┬ ノ( ゜-゜ノ)")
            elif cmd[0] == "ohyou": c.say("¯_(ツ)_/¯")
            elif cmd[0] == "FLIPTABLE": c.say("(ノಠ益ಠ)ノ彡┻━┻")
            elif cmd[0] == "fff": c.say("ლ(ಠ益ಠლ)")
            elif cmd[0] == "disapprove": c.say("ಠ_ಠ")
            elif cmd[0] == "crie": c.say("ಥ_ಥ")
            elif cmd[0] == "lenny": c.say("( ͡° ͜ʖ ͡°)")
            elif cmd[0] == "dongers": c.say("ヽ༼ຈل͜ຈ༽ノ")
            elif cmd[0] == "raise": c.say("ヽ༼ຈل͜ຈ༽ノ")
            elif cmd[0] == "butterfly": c.say("Ƹ̵̡Ӝ̵̨̄Ʒ")
            elif cmd[0] == "partytime": c.say("┏(-_-)┛┗(-_- )┓┗(-_-)┛┏(-_-)┓")
            elif cmd[0] == "fliptables": c.say("┻━┻︵ \(°□°)/ ︵ ┻━┻")
            elif cmd[0] == "polarbear": c.say("ˁ˚ᴥ˚ˀ")
            elif cmd[0] == "gun": c.say("︻╦╤─")
            elif cmd[0] == "pirate": c.say("✌(◕‿-)✌")
            elif cmd[0] == "happybirthday": c.say("¸¸♬·¯·♩¸¸♪·¯·♫¸¸Happy Birthday To You¸¸♬·¯·♩¸¸♪·¯·♫¸¸")
            elif cmd[0] == "sunglasses": c.say("( •_•) ( •_•)>⌐■-■ (⌐■_■)")
            elif cmd[0] == "rage": c.say("t(ಠ益ಠt)")
            elif cmd[0] == "cards": c.say("[♥]]] [♦]]] [♣]]] [♠]]]")
            elif cmd[0] == "gimme": c.say("༼ つ ◕_◕ ༽つ")
            elif cmd[0] == "monocle": c.say("ಠ_ರೃ")
            elif cmd[0] == "ghost": c.say("‹’’›(Ͼ˳Ͽ)‹’’›")
            elif cmd[0] == "why": c.say("ლ(`◉◞౪◟◉‵ლ)")
            elif cmd[0] == "praise": c.say("し(*・∀・)/♡\(・∀・*)ノ")
            elif cmd[0] == "lennyy": c.say(" ̿̿ ̿̿ ̿̿ ̿'̿'\̵͇̿̿\з=( ͡° ͜ʖ ͡°)=ε/̵͇̿̿/’̿’̿ ̿ ̿̿ ̿̿ ̿̿ ")
            # tears can be potentially dangerous, limited to admin +
            elif cmd[0] == "tears" and rank >= 3: c.say(" Ỏ̷͖͈̞̩͎̻̫̫̜͉̠̫͕̭̭̫̫̹̗̹͈̼̠̖͍͚̥͈̮̼͕̠̤̯̻̥̬̗̼̳̤̳̬̪̹͚̞̼̠͕̼̠̦͚̫͔̯̹͉͉̘͎͕̼̣̝͙̱̟̹̩̟̳̦̭͉̮̖̭̣̣̞̙̗̜̺̭̻̥͚͙̝̦̲̱͉͖͉̰̦͎̫̣̼͎͍̠̮͓̹̹͉̤̰̗̙͕͇͔̱͕̭͈̳̗̭͔̘̖̺̮̜̠͖̘͓̳͕̟̠̱̫̤͓͔̘̰̲͙͍͇̙͎̣̼̗̖͙̯͉̠̟͈͍͕̪͓̝̩̦̖̹̼̠̘̮͚̟͉̺̜͍͓̯̳̱̻͕̣̳͉̻̭̭̱͍̪̩̭̺͕̺̼̥̪͖̦̟͎̻̰_á»")
            
            #! other !#
            elif cmd[0] == "rps":
                target = cmd[1]
                global rps
                rps = games.RockPaperScissors(nick, target)
                c.msg(nick + " has challenged you to a game of rock, paper scissors.", target)
                c.msg("To participate, use " + f.BLUE + "/msg Oracle ?[rock/paper/scissors] (use /imsg if you're in-game)", target)
                c.msg("You have 30 seconds.", target)
                c.msg("You have challenged " + target + " to a game of rock, paper scissors.", nick)
                c.msg("To participate, use " + f.BLUE + "/msg Oracle ?[rock/paper/scissors] (use /imsg if you're in-game)", nick)
                c.msg("You have 30 seconds.", nick)
                
            
            elif cmd[0] == "rock" or cmd[0] == "paper" or cmd[0] == "scissors":
                if rps != None:
                    if rps.guess(cmd[0], nick):
                        c.msg("Decision accepted", nick)
                        c.msg("Your opponent has made a decision", rps.get_opponent(nick))
                    else:
                        c.msg("You're not in this RPS game!", nick)
                else:
                    c.msg("There is no RPS game at the moment.", nick)
                    
            elif cmd[0] == "a":
                global trivia
                trivia.guess(cmd[1:], nick)
            
            elif cmd[0] == "help" or cmd[0] == "what":
                if(len(cmd) < 2): help_(nick, "no")
                else: help_(nick, cmd[1])
                
            elif cmd[0] == "cb": cb(cmd[1:], nick)
            
            elif cmd[0] == "pick":
                c.say(nick + ": " + misc.pick(cmd[1:]))
                
            elif cmd[0] == "diamonds":
                if config.get('rick-roll'):
                    gags.rick_roll(nick, cmd[1])
                else:
                    c.msg(f.WHITE + "64 diamonds have been credited to the Minecraft account " + f.RED + nick + f.WHITE + ".", nick)
                    time.sleep(5)
                    c.msg("Just kidding.", nick)
                    c.msg("This command has been disabled in the config.", nick)
                    
            elif cmd[0] == "ayylmao":
                c.say("http://puu.sh/6wo5D.png")
                
            elif cmd[0] == "score":
                if cmd[1] == "check":
                    if len(cmd) > 2 and rank >= 3:
                        c.msg(cmd[2] + " has " + str(score.get(cmd[2])) + " points.", nick)
                    else:
                        c.msg("Your have " + str(score.get(nick)) + " points.", nick)
                elif cmd[1] == "top":                        
                    list = score.get_leader_boards()
                    amount = int(cmd[2]) if len(cmd) > 2 else 5
                    i = 1
                    for line in list:
                        c.msg(str(i) + ". " + line[0] + " - " + str(line[1]), nick)
                        i += 1
                        if i > amount:
                            break
                            
            elif cmd[0] == "resolve":
                data = socket.gethostbyname_ex(" ".join(cmd[1:]))
                c.say(" ".join(cmd[1:]) + " resolved to " + repr(data[2]))
                
            #! server !#
            elif cmd[0] == "events":
                results = e.get()
                
                if results:
                    c.say(f.BOLD + "Event: " + results[0] + " || " + f.BOLD + "Time" + f.BOLD + ": " + results[1] + " UTC")
                else:
                    c.say(f.BOLD + "No events found" + f.BOLD + " - there may be none planned.")
                    
            elif cmd[0] == "utc":
                c.say(e.utc() + " UTC")
                
            elif cmd[0] == "nether":
                c.msg(misc.netherposition(int(cmd[1]), int(cmd[2]), int(cmd[3])), nick)
                
            elif cmd[0] == "overworld":
                c.msg(misc.overworldposition(int(cmd[1]), int(cmd[2]), int(cmd[3])), nick)
      
            #! personal !#
            elif cmd[0] == "mail":
                try:
                    if cmd[1].lower() == "check":
                        if not m.check(nick):
                            c.msg("You have no mail.", nick)
                        else:
                            c.msg("Use ?mail read [mail]: "+ ", ".join(m.check(nick)), nick)
                            
                    elif cmd[1].lower() == "send":
                        text = " ".join(cmd[4:])
                        if m.send(nick, cmd[2], cmd[3], text):
                            c.msg("Message sent.", nick)
                        else:
                            c.msg("Message failed to send.", nick)
                            
                    elif cmd[1].lower() == "read":
                        c.msg(m.read(nick, cmd[2]), nick)
                        
                    elif cmd[1].lower() == "delete" or cmd[1].lower() == "del":
                        if m.delete(nick, cmd[2]):
                            c.msg("Message deleted.", nick)
                        else:
                            c.msg("Message not deleted.", nick)
                            
                    else:
                        c.msg("Usage: ?mail [check|send|read|delete]", nick)
                        
                except:
                    traceback.print_exc()
                    c.msg("Usage: ?mail [check|send|read|delete]", nick)
                    
            elif cmd[0] == "notes":
                try:
                    if cmd[1].lower() == "new":
                        text = " ".join(cmd[3:])
                        if n.new(cmd[2], text):
                            c.msg("Note successfully created.", nick)
                        else:
                            c.msg("Note already exists with that file name", nick)
                            
                    elif cmd[1].lower() == "delete":
                        if n.delete(cmd[2]):
                            c.msg("Note successfully deleted.", nick)
                        else:
                            c.msg("Deletion failed", nick)
                            
                    elif cmd[1].lower() == "edit":
                        text = " ".join(cmd[3:])
                        n.edit(cmd[2], text[1])
                        
                    elif cmd[1].lower() == "listall":
                        c.msg(" ".join(n.listall()), nick)
                        
                    elif cmd[1].lower() == "search" or cmd[1].lower() == "list":
                        c.msg(" ".join(n.find(cmd[2])), nick)
                        
                    elif cmd[1].lower() == "get":
                        c.msg(nick + ": " + n.get(cmd[2]), nick)
                        
                    else:
                        c.msg("Usage: ?notes [new|delete|edit|listall|search|get]", nick)
                except:
                    traceback.print_exc()
                    c.msg("Usage: ?notes [new|delete|edit|listall|search|get]", nick)
                    
            elif cmd[0] == "eval":
                try:
                    sm = " ".join(cmd[1:])
                    c.say(sm + " = " + str(eval(sm)))
                except:
                    traceback.print_exc()
        else:
            c.msg("Seems like you don't have access to these commands. Message an admin for help.", nick)
            
        #! moderator !#
        # rank = 2
        if rank >= 2:
            if cmd[0] == "say":
                c.say(format.replace(" ".join(cmd[1:])))
            
            elif cmd[0] == "ATTENTION":
                global ATTENTION
                ATTENTION = True
                c.getusers()
                
            elif cmd[0] == "ban" :
                v.setvar(nick, cmd[1], "rank", 0)
                c.msg("User: "******" has been banned.", nick)
                
            elif cmd[0] == "kick":
                if len(cmd) < 3:
                    c.kick(cmd[1], "")
                    c.msg("User kicked.", nick)
                else:
                    c.kick(cmd[1], " ".join(cmd[2:]))
                    c.msg("User kicked for " + " ".join(cmd[2:]) + ".", nick)
        
        #! admin !#
        # rank = 3
        if rank >= 3:
            if cmd[0] == "close":
                c.stop(nick)
                EXIT = True
                
            elif cmd[0] == "restart" :
                c.restart(nick)
                
            elif cmd[0] == "reload":
                log("Reload issued by " + nick, m_type="RELOAD", colour=Fore.YELLOW, reset=False)
                reload_()
                c.say(f.YELLOW + "Reload complete.")
                
            elif cmd[0] == "sreload":
                reload_()
                c.msg(f.YELLOW + "Silent reload complete.", nick)
                
            elif cmd[0] == "setrank":
                v.setvar(cmd[1], "rank", int(cmd[2]))
                c.msg(cmd[1] + "'s rank set to " + cmd[2] + ".", nick)
                
            elif cmd[0] == "mode":
                c.mode(cmd[1:])
                
            elif cmd[0] == "getrank":
                c.msg(cmd[1] + "'s rank is " + str(v.getvar(cmd[1], "rank")) + ".", nick)
                
            elif cmd[0] == "flood":
                if cmd[1] == "reset":
                    spam.clear()
                    c.msg("Cleared FLOOD dictionary", nick)
                elif cmd[1] == "decrement":
                    spam.decrement()
                    c.msg("FLOOD decrement performed", nick)
                    
            elif cmd[0] == "randompoints":
                if cmd[1] == "run":
                    randompoints.poll_users()
                    time.sleep(1)
                    randompoints.reward()
                
            elif cmd[0] == "trivia":
                if cmd[1] == "new":
                    c.say("[" + f.PURPLE + "Trivia" + f.WHITE + "] New round started by " + f.BLUE + nick)
                    trivia._runnable()
                elif cmd[1] == "off":
                    trivia.disable()
                    c.say("[" + f.PURPLE + "Trivia" + f.WHITE + "] Disabled by " + f.BLUE + nick)
                elif cmd[1] == "on":
                    if trivia._getdisabled():  
                        del trivia
                        trivia = games.trivia()
                        c.say("[" + f.PURPLE + "Trivia" + f.WHITE + "] Re-enabled by " + f.BLUE + nick)
                elif cmd[1] == "info":
                    c.msg(trivia.getinfo(), nick)
                    
            elif cmd[0] == "score":
                if cmd[1] == "reset":
                    if score.reset(cmd[2]):
                        c.msg("Successfully reset " + cmd[2] + "'s score.", nick)
                    else:
                        c.msg("Reset failed.", nick)
                elif cmd[1] == "add":
                    points = score.add(cmd[2], cmd[3])
                    if not points:
                        c.msg("Points failed to add.", nick)
                    else:
                        c.msg("Sucessfully added points, " + cmd[2] + " now has " + str(points) + " points.", nick)
                        
            elif cmd[0] == "ignore":
                try:
                    IGNORE_LIST.append(cmd[1])
                    c.msg("Successfuly added " + cmd[1] + " to ignore list.", nick)
                except:
                    c.msg("Ignore unsuccessful.", nick)
                
            elif cmd[0] == "pardon":
                try:
                    del ingore_list[cmd[1]]
                    c.msg("Successfully pardoned " + cmd[1] + ".", nick)
                except:
                    c.msg("Pardon unsuccessful. Perhaps " + cmd[1] + " is not currently being ignored.", nick)
                        
        #! developer !#
        # rank = 4
        if rank >= 4:
            if cmd[0] == "makevar":
                target = cmd[1]
                
                if(v.makevarfile(target)):
                    ACTION_LOG.info(Fore.RED + "!!!" + Fore.RESET + " - New var file created for " + target + " by " + nick)
                    c.msg("VAR file successfully created for " + target, nick)
                else:
                    ACTION_LOG.info(Fore.RED + "!!!" + Fore.RESET + " - Var file creation failed - " + nick)
                    c.msg("VAR file failed to create for " + target, nick)
                    
            elif cmd[0] == "getvar":
                response = v.getvar( cmd[1], cmd[2])
                c.msg("VAR: %s = %s" % (cmd[2], response),nick)
                    
            elif cmd[0] == "listvar":
                response = v.listvar(cmd[1])
                c.msg(response, nick)
                
            elif cmd[0] == "setvar":
                if(v.setvar(cmd[1], cmd[2], int(cmd[3]))):
                    c.msg("VAR: %s set to %s for %s" % (cmd[2], cmd[3], cmd[1]), nick)
                else:
                    c.msg("Setting of variable failed.", nick)
                    
            elif cmd[0] == "deletevar":
                if(v.deletevarfile(cmd[1])):
                    c.msg("VAR file successfully deleted.", nick)
                else:
                    c.msg("VAR file deletion failed.", nick)
                
            elif cmd[0] == "resetvar":
                target = cmd[1]
                
                if(v.deletevarfile(target)):
                    c.msg("VAR file successfully deleted.", nick)
                else:
                    c.msg("VAR file deletion failed.")
                    
                if(v.makevarfile(target)):
                    ACTION_LOG.info(Fore.RED + "!!!" + Fore.RESET + " - New var file created for " + target + " by " + nick)
                    c.msg("VAR file successfully created for " + target, nick)
                else:
                    ACTION_LOG.info(Fore.RED + "!!!" + Fore.RESET + " - Var file creation failed - " + nick)
                    c.msg("VAR file failed to create for " + target, nick)
                    
            elif cmd[0] == "formats" :
                c.say(vars(f))
                    
            elif cmd[0] == "cls":
                os.system("cls")
                
            elif cmd[0] == "join":
                join(nick)
                
            elif cmd[0] == "joinn":
                join(cmd[1])
                
            elif cmd[0] == "raw":
                c.raw(cmd[1:])
                
            elif cmd[0] == "config":
                if cmd[1] == "reload":
                    try:
                        config.reload()
                        c.msg("Config reloaded.", nick)
                    except:
                        traceback.print_exc()
                        c.msg("Error reloading config", nick)
                elif cmd[1] == "set":
                    try:
                        config.set(cmd[2], cmd[3:])
                        c.msg("Config set.", nick)
                    except:
                        traceback.print_exc()
                        c.msg("Error setting config", nick)
                elif cmd[1] == "get":
                    try:
                        c.msg(config.get(cmd[2]), nick)
                    except:
                        traceback.print_exc()
                        c.msg("Error getting config", nick)
                        
            elif cmd[0] == "testlog":
                log("No string test")
                log("Action test", l_type='action', m_type="TESTLOG", colour=Fore.GREEN)
                if len(cmd) > 1:
                    log(' '.join(cmd[1:]), colour=Fore.GREEN, m_type="TESTLOG")
                    
            elif cmd[0] == "exec":
                try:
                    exec " ".join(cmd[1:])
                except:
                    c.say(traceback.print_exc())
                        
    except SystemExit:
        return
        
    except:
        # any and every error will throw this
        traceback.print_exc()
        c.msg("Oops! Something went wrong. Please contact an admin for help.",nick)
Пример #8
0
 def cvt(events, waiters):
     for event in events.get():
         event.trigger()
         for waiter in event.waiters:
             waiters.put(waiter)
Пример #9
0
 def cvt(events, waiters):
     for event in events.get():
         event.trigger()
         for waiter in event.waiters:
             waiters.put(waiter)
Пример #10
0
def update():
    """Update ball/paddle/bricks based on physics"""

    #Keep track of variables changes with gameplay
    score = 0
    lives = 0

    #Update paddle location
    location = PADDLE.sprites()[0].rect.left
    offset = 0

    if events.get("LEFT", 0) or events.get("LEFT", 1):
        offset = -16
        if location + offset < 0: offset = 0

    if events.get("RIGHT", 0) or events.get("RIGHT", 1):
        offset = 16
        if location + offset > 1152: offset = 0

    PADDLE.sprites()[0].update(x=offset)

    #Update ball locations
    for i in BALLS.sprites():
        v = i.custom['v']

        #Collisions
        ballEdge = (i.rect.topleft[0], i.rect.topleft[1],
                    i.rect.topleft[0] + 16, i.rect.topleft[1] + 16)
        collide = None

        #Screen edge collisions
        if ballEdge[0] <= 0 or ballEdge[2] >= 1280:
            collide = 'x'
            noise.play('bounce')
        if ballEdge[1] <= 32:
            collide = 'y'
            noise.play('bounce')
        if ballEdge[3] >= 780:
            lives = -1
            i.remove(BALLS)
            noise.play('miss')
            break

        collisions = pygame.sprite.spritecollide(i, BRICKS,
                                                 0)  #Brick collisions
        if len(collisions) > 0:
            for j in collisions:  #For each collision...

                score += 250
                j.custom['i'] -= 1
                if j.custom['i'] < 0:  #Remove brick if it was the final brick
                    j.remove(BRICKS)
                    noise.play('break')

                else:  #Reduce brick in toughness
                    j.image = img.CACHE['brick%i' % j.custom['i']]
                    noise.play('bounce')

                if i.rect.top <= j.rect.bottom and i.custom['v'][1] > 0:
                    collide = 'y'
                if i.rect.bottom >= j.rect.top and i.custom['v'][1] < 0:
                    collide = 'y'
                if i.rect.left <= j.rect.right and i.custom['v'][
                        0] < 0 and i.rect.right > j.rect.right:
                    collide = 'x'
                if i.rect.right >= j.rect.left and i.custom['v'][
                        0] > 0 and i.rect.left < j.rect.left:
                    collide = 'x'

        collisions = pygame.sprite.spritecollide(i, PADDLE,
                                                 0)  #Paddle collision
        if len(collisions) > 0:
            paddleXY = collisions[0].rect.topleft
            paddleCenter = collisions[0].rect.centerx
            ballCenter = i.rect.centerx
            hitBox = ballCenter - paddleCenter
            newX = float(hitBox) / (paddleCenter - paddleXY[0])
            if newX > 0.45: hitPercent = 0.45
            elif newX < -0.45: hitPercent = -0.45

            if newX >= 0: newY = 1 - newX
            elif newX < 0: newY = 1 + newX

            i.custom['v'] = [newX, newY]
            noise.play('bounce')

        if collide == 'x': i.custom['v'][0] *= -1
        if collide == 'y': i.custom['v'][1] *= -1

        #Update ball location based off magnitude and rise/run
        x = int(round(i.custom['v'][0] * 16, 0))
        y = int(round(i.custom['v'][1] * 16 * -1, 0))

        i.update(x, y)

    return (score, lives)
Пример #11
0
def event_list():
    return render_template('event_list.html', event_list=events.get())
Пример #12
0
            else:
                self.scr.addstr(y, x + i, c, attr)
                attr = 0


if __name__ == "__main__":
    scr = initscr()
    keychars = PyGameThread()
    keychars.start()
    scr.addstr(1, 1, 'Hello')
    scr.addstr(2, 1, 'Hello')
    scr.addstr(3, 2, 'Hello')
    scr.refresh()
    while True:
        try:
            ev = events.get()
        except Exception:
            continue

        if ev.event_type == events.EVENT_KEY_DOWN:
            if ev.key_code == pygame.K_q:
                break
        scr.addstr(1, 1, 'Hello')
        scr.addstr(2, 1, 'Hello')
        scr.addstr(3, 2, 'Hello')
        scr.refresh()
    scr.textbox(4, 1, 30, 'Test Value', edit=True)
    scr.listbox(4, 1, 30, 'Test Value', options=['aa', 'bb', 'cc'], edit=True)

    command, parameters = Menu(scr,
                               commands=[
Пример #13
0
 def update(self):
     if events.get("CANCEL", 0): return 1
     else: return Menu.update(self)
Пример #14
0
    def run(self):
        row_keys = {keys.KEY_UP: -1, keys.KEY_DOWN: 1}
        move_pattern_keys = {keys.KEY_SR: -1, keys.KEY_SF: 1}
        self.refresh()
        while True:
            try:
                ev = events.get()
            except Exception:
                continue

            if ev.event_type == events.EVENT_QUIT:
                break

            if ev.event_type != events.EVENT_KEY_DOWN:
                continue

            k, c = ev.key_code, ev.char
            if c == ':':
                command, parameters = sdlcurses.Menu(self.scr, commands=[
                    ('n', ['_New Project']),
                    ('o', ['_Open Project']),
                    ('s', ['_Save Project']),
                    ('np', ['_New', '_Pattern']),
                    ('dp', ['_Duplicate', '_Pattern']),
                    ('ep', ['_Edit', '_Pattern']),
                    ('epn', ['_Edit', '_Pattern', '_Name']),
                    ('rp', ['_Remove', '_Pattern']),
                    ('bpm', ['_Beats _per _minute']),
                    ('q', ['_Quit']),
                ]).run()

                if command == 'q':
                    break
                elif command == 'n':
                    self.player.stop()
                    self.project = project.create_empty_project()
                elif command == 'o':
                    with open('{}.json'.format(parameters), 'r') as f:
                        self.project.load(json.loads(f.read()))
                elif command == 's':
                    with open('{}.json'.format(parameters), 'w') as f:
                        f.write(json.dumps(self.project.dump(), indent=2))
                elif command == 'np':
                    self._new_pattern(parameters)
                elif command == 'dp':
                    self._duplicate_pattern()
                elif command == 'ep':
                    self._edit_pattern()
                elif command == 'epn':
                    if parameters:
                        self._pattern.name = parameters
                elif command == 'rp':
                    self._remove_pattern()
                elif command == 'bpm':
                    self._set_bpm(parameters)
            elif c == 'q' or k == keys.KEY_ESC:
                break
            elif k in row_keys:
                if self._seq_edit:
                    if self._seq_pos is not None:
                        self._seq_pos = (
                            (self._seq_pos + row_keys[k]) %
                            len(self.project.patterns_seq)
                        )
                elif self.project.patterns and self._pattern:
                    self._pattern = self.project.patterns[
                        (self._pattern_idx() + row_keys[k])
                        % len(self.project.patterns)
                    ]
                    if (self.player.playing() and
                            issubclass(
                                self.player.data.__class__, project.Pattern)):
                        self.player.mute()
                        self.player.play(self._pattern)
            elif k in move_pattern_keys:
                if self._seq_edit:
                    pseq = self.project.patterns_seq
                    i = self._seq_pos
                    j = (i + move_pattern_keys[k]) % len(pseq)
                    pseq[i], pseq[j] = pseq[j], pseq[i]
                    self._seq_pos = j
                    self.project.rebuild_sequence()
                else:
                    patterns = self.project.patterns
                    if len(patterns) < 2:
                        return
                    self.push_undo()
                    i = self._pattern_idx()
                    j = (i + move_pattern_keys[k]) % len(patterns)
                    patterns[i], patterns[j] = patterns[j], patterns[i]
            elif k in [keys.KEY_LEFT, keys.KEY_RIGHT]:
                self._seq_edit = not self._seq_edit
            elif k == keys.KEY_BACKSPACE:
                self.pop_undo()
            elif c == 'n':
                self._new_pattern(None)
            elif c == 'd':
                self._duplicate_pattern()
            elif c == 'r':
                if self._seq_edit:
                    if self._seq_pos is not None:
                        self.project.patterns_seq.pop(self._seq_pos)
                        self._seq_pos = min(self._seq_pos,
                                            len(self.project.patterns_seq)-1)
                        if self._seq_pos == -1:
                            self._seq_pos = None
                else:
                    self._remove_pattern()
                self.project.rebuild_sequence()
            elif k == keys.KEY_ENTER:
                self._edit_pattern()
            elif c == " ":
                if self.player.playing():
                    self.player.stop()
                else:
                    self.player.play(self._pattern)
            elif c == "+":
                self.push_undo()
                if self._seq_pos is None:
                    self._seq_pos = -1
                self._seq_pos += 1
                self.project.patterns_seq.insert(self._seq_pos,
                                                 self._pattern.uid)
                self.project.rebuild_sequence()
            elif c == 'p':
                self.project.rebuild_sequence()
                if self.player.playing():
                    self.player.stop()
                self.player.play(self.project)
            else:
                self._debug = 'DEBUG: KEY {} | CHAR "{}"'.format(k, c)

            self._seq_edit = self._seq_edit and len(self.project.patterns_seq)
            self.refresh()
Пример #15
0
    def run(self):
        delete_keys = self.delete_keys
        drum_keys = [k.lower() for k in delete_keys]
        drum_key_to_note = []
        for octave in xrange(6):
            drum_key_to_note += [n+(12*octave)
                                 for n in [48, 50, 52, 53, 55, 57, 59]]

        key_to_midi = ['a', 'w', 's', 'e', 'd', 'f', 't', 'g', 'y', 'h',
                       'u', 'j', 'k']
        key_to_midi_octave = 0
        key_to_midi_state = {}
        midi_state = set()

        row_keys = {keys.KEY_UP: -1, keys.KEY_DOWN: 1}
        move_track_keys = {keys.KEY_SR: -1, keys.KEY_SF: 1}
        shift_track_keys = {keys.KEY_SLEFT: 1, keys.KEY_SRIGHT: -1}
        offset_keys = {keys.KEY_LEFT: -1, keys.KEY_RIGHT: 1}
        octave_keys = {'-': -1, '+': 1}

        quantize_keys = ['1', '2', '3', '4', '0']

        pad = self.pad
        pad.erase()

        prev_time = None
        repaint = 0
        pad.find_font_size(self.pattern.len*3+20, len(self.pattern.tracks))
        while True:
            try:
                ev = events.get()
            except Exception:
                curr_time = int(self.player.get_time())
                if prev_time != curr_time:
                    prev_time = curr_time
                    self.paint(only_pos=True)

                continue

            if ev.event_type == events.EVENT_QUIT:
                events.put(ev)
                break

            if ev.event_type == events.EVENT_REFRESH:
                self.paint()
                continue

            if ev.event_type == events.EVENT_RESIZE:
                pad.resize(ev.width, ev.height)
                pad.find_font_size(self.pattern.len*3+20,
                                   len(self.pattern.tracks))
                self.paint()
                continue

            self._current_track = min(self._current_track,
                                      len(self.pattern.tracks) - 1)
            track = self.pattern.tracks[self._current_track]

            if ev.event_type == events.EVENT_MIDI_NOTE:
                # Process input values
                ntime = self.player.get_time()
                channel_note = (ev.channel, ev.note)
                if ev.midi_event_type == MIDI_EVENT_NOTE_ON:
                    if channel_note not in midi_state:
                        if self.rec:
                            track.note_on(ntime, ev.channel, ev.note,
                                          ev.velocity)
                        else:
                            track.seq_note_on(ev.channel, ev.note, ev.velocity)
                        midi_state.add(channel_note)
                elif ev.midi_event_type == MIDI_EVENT_NOTE_OFF:
                    if channel_note in midi_state:
                        if self.rec:
                            track.note_off(ntime, ev.channel, ev.note)
                        else:
                            track.seq_note_off(ev.channel, ev.note)

                        try:
                            midi_state.remove(channel_note)
                        except Exception:
                            pass

                    if not midi_state:
                        self.push_undo()
            elif ev.event_type == events.EVENT_MIDI_CONTROLLER:
                seq.set_control(track._midi_port, ev.value, ev.param,
                                ev.channel)
            elif ev.event_type == events.EVENT_MIDI_PITCHBEND:
                ntime = self.player.get_time()
                if self.rec:
                    track.pitchbend(ntime, ev.value, ev.channel)
                else:
                    track.seq_pitchbend(ev.value, ev.channel)

            elif ev.event_type == events.EVENT_KEY_DOWN:
                k = ev.key_code
                c = ev.char
                if c == ':':
                    command, parameters = sdlcurses.Menu(pad, commands=[
                        ('pl', ['_Pattern _Length']),
                        ('nd', ['_New', '_Drum Channel']),
                        ('nm', ['_New', '_Midi Channel']),
                        ('cp', ['_Clear _Pitchbend']),
                        ('e', ['_Edit Channel']),
                        ('en', ['_Edit Channel _Name']),
                        ('d', ['_Duplicate Channel']),
                        ('r', ['_Remove Channel']),
                        ('bpm', ['_Beats _per _minute']),
                    ]).run()

                    if command == 'nd':
                        name = parameters or 'Drum Channel'
                        track = project.DrumTrack(name, [' '] * track.len(),
                                                  "", 15, 44)
                        self.pattern.tracks.append(track)
                        self._current_track = len(self.pattern.tracks) - 1
                        TrackEditor(pad, track).run()
                    elif command == 'nm':
                        name = parameters or 'Midi Channel'
                        track = project.MidiTrack(name, track.len(), [],
                                                  [0] * track.len(), "", 0)
                        self.pattern.tracks.append(track)
                        self._current_track = len(self.pattern.tracks) - 1
                        TrackEditor(pad, track).run()
                    elif command == 'cp':
                        for i in xrange(track.len()):
                            track.clear(
                                i,
                                MIDI_EVENT_PITCH
                            )
                    elif command == 'd':
                        tmp_track = track.__class__()
                        tmp_track.load(track.dump())
                        self.pattern.tracks.append(tmp_track)
                        self._current_track = len(self.pattern.tracks) - 1
                    elif command == 'r':
                        self.pattern.tracks.remove(track)
                        self._current_track = min(self._current_track,
                                                  len(self.pattern.tracks) - 1)
                        pad.erase()
                    elif command == 'e':
                        TrackEditor(pad, track).run()
                    elif command == 'en':
                        track.name = parameters
                    elif command == 'bpm':
                        set_bpm(parameters, self.project)
                    elif command == 'pl':
                        self.pattern.resize(int(parameters))

                elif c in key_to_midi + drum_keys:
                    midi_note = None
                    if track.track_type == TRACK_TYPE_DRUM:
                        if c in drum_keys:
                            pos = drum_keys.index(c)
                            pos += self._track_offset * len(delete_keys)
                            midi_note = drum_key_to_note[pos]
                    else:
                        midi_note = (key_to_midi.index(c)
                                     + key_to_midi_octave * 12 + 60)

                    if not key_to_midi_state.get(midi_note):
                        events.put(events.MidiNoteEvent(MIDI_EVENT_NOTE_ON,
                                                        track.midi_channel,
                                                        midi_note, 127))
                        key_to_midi_state[midi_note] = True
                elif c == " ":
                    if self.player.playing():
                        self.player.stop()
                    else:
                        self.player.play(self.pattern)
                elif k in row_keys:
                    self._current_track = ((self._current_track + row_keys[k])
                                           % len(self.pattern.tracks))
                elif k in move_track_keys:
                    i = self._current_track
                    j = (i + move_track_keys[k]) % len(self.pattern.tracks)
                    self.pattern.tracks[i], self.pattern.tracks[j] = (
                        self.pattern.tracks[j], self.pattern.tracks[i]
                    )
                    self._current_track = (
                        (self._current_track + move_track_keys[k])
                        % len(self.pattern.tracks)
                    )
                elif k in shift_track_keys:
                    track.shift(shift_track_keys[k])
                elif k in offset_keys:
                    self._track_offset = (
                        (self._track_offset + offset_keys[k])
                        % (self.pattern.len / len(delete_keys))
                    )
                elif c in octave_keys:
                    key_to_midi_octave += octave_keys[c]
                elif c in delete_keys:
                    pos = (delete_keys.index(c) +
                           self._track_offset * len(delete_keys))
                    track.clear(pos)
                    self.push_undo()
                elif c in quantize_keys:
                    if True or track.track_type == TRACK_TYPE_DRUM:
                        pos = self._track_offset * len(delete_keys)
                        for i in range(len(delete_keys)):
                            track.quantize(pos + i, c)
                        self.push_undo()
                elif c == 'R':
                    self.rec = not self.rec
                elif k == keys.KEY_BACKSPACE:
                    self.pop_undo()
                elif k == keys.KEY_ENTER:
                    TrackEditor(pad, track).run()
                elif c == 'q' or k == keys.KEY_ESC:
                    break
            elif ev.event_type == events.EVENT_KEY_UP:
                k = ev.key_code
                c = chr(k & 0xff)
                if c in key_to_midi + drum_keys:
                    midi_note = None
                    if track.track_type == TRACK_TYPE_DRUM:
                        if c in drum_keys:
                            pos = drum_keys.index(c)
                            pos += self._track_offset * len(delete_keys)
                            midi_note = drum_key_to_note[pos]
                    else:
                        midi_note = (key_to_midi.index(c)
                                     + key_to_midi_octave * 12 + 60)

                    if key_to_midi_state.get(midi_note):
                        events.put(events.MidiNoteEvent(MIDI_EVENT_NOTE_OFF,
                                                        track.midi_channel,
                                                        midi_note, 127))
                        key_to_midi_state[midi_note] = False

            nowtime = time.time()
            if repaint < nowtime - 0.05:
                self._octave = key_to_midi_octave
                self.paint()
                repaint = nowtime
Пример #16
0
def event_list():
    return render_template('event_list.html', event_list=events.get())
Пример #17
0
def get_event_or_404(eid):
    try:
        return events.get(eid)
    except KeyError:
        abort(404)
Пример #18
0
Файл: tool.py Проект: kcsaff/CA
def handle_events(window, event_map):
    for event in events.get([window.lib]):
        fun = event_map.get(event.type, do_nothing)
        fun(window, event)
Пример #19
0
def get_event_or_404(eid):
    try:
        return events.get(eid)
    except KeyError:
        abort(404)
Пример #20
0
def update():
  """Update ball/paddle/bricks based on physics"""
  
  #Keep track of variables changes with gameplay
  score = 0
  lives = 0

  #Update paddle location
  location = PADDLE.sprites()[0].rect.left
  offset = 0
  
  if events.get("LEFT", 0) or events.get("LEFT", 1):
    offset = -16
    if location + offset < 0: offset = 0
      
  if events.get("RIGHT", 0) or events.get("RIGHT", 1):
    offset = 16
    if location + offset > 1152: offset = 0
    
  PADDLE.sprites()[0].update(x=offset)
  
  #Update ball locations
  for i in BALLS.sprites():
    v = i.custom['v']
    
    #Collisions
    ballEdge = (i.rect.topleft[0], i.rect.topleft[1], i.rect.topleft[0]+16, i.rect.topleft[1]+16)
    collide = None
    
    #Screen edge collisions
    if ballEdge[0] <= 0 or ballEdge[2] >= 1280:
      collide = 'x'
      noise.play('bounce')
    if ballEdge[1] <= 32:
      collide = 'y'
      noise.play('bounce')
    if ballEdge[3] >= 780:
      lives = -1
      i.remove(BALLS)
      noise.play('miss')
      break
     
    collisions = pygame.sprite.spritecollide(i, BRICKS, 0) #Brick collisions
    if len(collisions) > 0:
      for j in collisions: #For each collision...

        score += 250
        j.custom['i'] -= 1
        if j.custom['i'] < 0: #Remove brick if it was the final brick
          j.remove(BRICKS)
          noise.play('break')
          
        else: #Reduce brick in toughness
          j.image = img.CACHE['brick%i' % j.custom['i']]
          noise.play('bounce')
  
        if i.rect.top <= j.rect.bottom and i.custom['v'][1] > 0: collide = 'y'
        if i.rect.bottom >= j.rect.top and i.custom['v'][1] < 0: collide = 'y'
        if i.rect.left <= j.rect.right and i.custom['v'][0] < 0 and i.rect.right > j.rect.right:
          collide = 'x'
        if i.rect.right >= j.rect.left and i.custom['v'][0] > 0 and i.rect.left < j.rect.left:
          collide = 'x'

        
    collisions = pygame.sprite.spritecollide(i, PADDLE, 0) #Paddle collision
    if len(collisions) > 0:
      paddleXY = collisions[0].rect.topleft
      paddleCenter = collisions[0].rect.centerx
      ballCenter = i.rect.centerx
      hitBox = ballCenter - paddleCenter
      newX = float(hitBox) / (paddleCenter - paddleXY[0])
      if newX > 0.45: hitPercent = 0.45
      elif newX < -0.45: hitPercent = -0.45
      
      if newX >= 0: newY = 1 - newX
      elif newX < 0: newY = 1 + newX
      
      i.custom['v'] = [newX, newY]
      noise.play('bounce')
      
    if collide == 'x': i.custom['v'][0] *= -1
    if collide == 'y': i.custom['v'][1] *= -1
    
    #Update ball location based off magnitude and rise/run
    x = int( round(i.custom['v'][0] * 16, 0) )
    y = int( round(i.custom['v'][1] * 16 * -1, 0) )
    
    i.update(x,y)
    
  return (score, lives)