Example #1
0
def insert(cur, db):
    if db == 'sqlite':
        cur.executemany('INSERT INTO USERS VALUES(?,?,?)',
                        [(who, uid, rrange(1, 5)) for who, uid, in randNmae()])
    elif db == 'mysql':
        cur.executemany('INSERT INTO USERS VALUES(%s,%s,%s)',
                        [(who, uid, rrange(1, 5)) for who, uid, in randNmae()])
Example #2
0
    def __init__(self, uid: str, index: int, numGames: int, drawRatio: float,
                 rating: int):
        self._id = uid + "/" + str(index)
        self.userId = uid
        self.perfType = index
        self.bestWins = self._results()
        self.worstLosses = self._results()

        variantVariance = random.uniform(-0.03,
                                         0.03)  # best variable name ever
        winRatio = 0.5 + variantVariance
        r = rating + int(8000 * variantVariance)  # ass math at its best
        draw = int(numGames * random.uniform(drawRatio / 5, drawRatio))
        win = int(numGames * winRatio - draw / 2)

        self.r = r
        self.resultStreak = {"win": self._streak(), "loss": self._streak()}
        self.playStreak = {"nb": self._streak(), "time": self._streak()}

        self.count = {
            "all": numGames,
            "rated": int(numGames * random.uniform(0.7, 0.99)),
            "draw": draw,
            "win": win,
            "loss": numGames - win - draw,
            "tour": rrange(20, 150),
            "berserk": rrange(0, 50),
            "opAvg": {
                "avg": 1 - winRatio,
                "pop": rrange(10, 100)
            },
            "seconds": numGames * 300,
            "disconnects": rrange(2, 40),
        }
Example #3
0
 def update(self):
     fr = rrange(1,5)
     to = rrange(1,5)
     users = self.users.selectBy(prid=fr)
     for i, user in enumerate(users):
         user.prid = to
     return fr, to, i+1
Example #4
0
    def die_roll(self, num=1):
        die1 = rrange(10)
        die2 = rrange(10)

        roll = int(str(die1) + str(die2))

        return roll
 def update(self):
     fr = rrange(1, 5)
     to = rrange(1, 5)
     users = self.users.selectBy(prid=fr)
     for i, user in enumerate(users):
         user.prid = to
     return fr, to, i + 1
def insert(cur, db):
    if db == 'sqlite':
        cur.executemany("insert into users values(?,?,?)",
                        [(who, uid, rrange(1, 5)) for who, uid in randName()])
    elif db == 'mysql':
        cur.executemany("insert into users values(%s, %s, %s)",
                        [(who, uid, rrange(1, 5)) for who, uid in randName()])
def creature_appearance(num=1):
    ## uses DB info of creature frequency ##
    for each in range(num):
        die1 = rrange(50)
        die2 = rrange(50) # appearance rolls
        creature_select = choice(list(creatures.keys()))
        print('ROOMS CREATURES BEFORE: {}'.format(rooms_creatures))
        room_ = rooms[room_temp['room']][0]

        if creatures[creature_select]['freq'] >= die1+die2 and room_ not in list(rooms_creatures.keys()):
            #print('DEBUG::{}: is appearing, roll was {}:{}'.format(creatures[creature_select]['name'],
            # die1+die2,
            # creatures[creature_select]['freq']))
            print('ROOMS TEMP',rooms[room_temp['room']][0])
            if rooms[room_temp['room']][0] not in list(rooms_creatures.keys()):
                #don't add another creature if one is already in room..

                #rooms_creatures[rooms[room_temp]['room']][0]['creatures'].append(creatures[creature_select]['name'])
                rooms_creatures[room_] = [creatures[creature_select]['name']]
            print('ROOMS CREATURES AFTER: {}'.format(rooms_creatures))
            return (rooms_creatures[room_][0],True)

        elif creatures[creature_select]['freq'] >= die1+die2 and room_ in list(rooms_creatures.keys()):
           #print('DEBUG::{}: is not appearing, roll was {}:{}'.format(creatures[creature_select]['name'],
           # die1+die2,
           # creatures[creature_select]['freq']))
            return(rooms_creatures[room_][0],True)

        else:
            return(0,False)
Example #8
0
def insert(cur, db):
    if db == 'sqlite':
        cur.executemany("INSERT INTO users VALUES(?, ?, ?)", [(who, uid, rrange(1, 5)) for who, uid in randName()])
    elif db == 'gadfly':
        for who, uid in randName():
            cur.execute("INSERT INTO users VALUES(?, ?, ?)", (who, uid, rrange(1, 5)))
    elif db == 'mysql':
        cur.executemany("INSERT INTO users VALUES(%s, %s, %s)", [(who, uid, rrange(1, 5)) for who, uid in randName()])
Example #9
0
def RMDice(sides = 100, nod = 1, rules = "MERS", low = 4, high = 96):
    '''
    This functions simulates the sides and number of dices thrown at RPG
    \param sides number of sides of the dice(s)
    \param nod number of dices
    \param rules MERS/MERP/RM rules activated
    \param low value to roll again and subtract second value
    \param high value to roll again and add second value
    \retval result list of result(s) of thrown dices
    \retval umr list of unmodified rolls (66 or 100)
    \return delivers a tuple of 2 arrays
    '''
    result = []
    umr = []
    
    if sides < 2:
        sides = 2
    
    if nod < 1:
        nod = 1
        
    for d in range(nod):
        throw = rrange(1, sides)
        if rules == "RM " or rules == "MERS":
            if throw <= low:
                throw2 = rrange(1, sides)
                dummy = throw2
                
                while throw2 >= high:
                    throw2 = rrange(1, sides)
                    dummy += throw2
                
                throw -= dummy
            
            elif throw == 66 and rules == "RM":
                umr.append ([d, 66])
                
            elif throw >= high:
                
                if throw == 100 and rules == "RM":
                    umr.append([d, 100])
                
                throw2 = rrange(1, sides)
                dummy = throw2
                
                while throw2 >= high:
                    throw2 = rrange(1, sides)
                    dummy += throw2
                    
                throw += dummy
        
        result.append(throw)
    
    return result, umr
Example #10
0
def insert(cur, db):
    if db == 'sqlite':
        cur.executemany("INSERT INTO users VALUES(?, ?, ?)",
                        [(who, uid, rrange(1, 5)) for who, uid in randName()])
    elif db == 'gadfly':
        for who, uid in randName():
            cur.execute("INSERT INTO users VALUES(?, ?, ?)",
                        (who, uid, rrange(1, 5)))
    elif db == 'mysql':
        cur.executemany("INSERT INTO users VALUES(%s, %s, %s)",
                        [(who, uid, rrange(1, 5)) for who, uid in randName()])
Example #11
0
def play(statedict):
    Refresh_av = statedict.get("Refresh")
    gmsg = "Playing game."
    try:
        choice_av = len(statedict.get("Choice"))
        while Refresh_av >= 0 or choice_av > 0:
            for key in statedict:
                print(key, "=", statedict.get(key))
            result = check_state(statedict)
            if not result:
                return statedict.get("Score")
            print("Press R to refresh or Enter to continue.")
            uinp3 = raw_input()
            if uinp3 == "r" or uinp3 == "R":
                Refresh_av -= 1

                new_testno = rrange(1, 10)
                statedict.update(dict({"Testno.": new_testno}))

                new_refresh = Refresh_av
                statedict.update(dict({"Refresh": new_refresh}))
                continue

            if statedict.get("Refresh") > 0:
                print("Please input your options.")
                uipt1 = raw_input()
                uipt2 = raw_input()

                if not (uipt2):
                    sum = int(uipt1)
                    statedict.get("Choice").remove(sum)
                else:
                    sum = int(uipt1) + int(uipt2)
                    statedict.get("Choice").remove(int(uipt1))
                    statedict.get("Choice").remove(int(uipt2))
                choice_av = len(statedict.get("Choice"))
                if sum == statedict.get("Testno."):

                    new_testno = rrange(1, 10)
                    statedict.update(dict({"Testno.": new_testno}))

                    new_Score = statedict.get("Score") + 1
                    statedict.update(dict({"Score": new_Score}))

                else:
                    return statedict.get("Score")
            elif statedict.get("Refresh") == 0:
                if statedict.get("Testno.") not in statedict.get("Choice"):
                    return statedict.get("Score")
        return statedict.get("Score")
    except Exception as e:
        emsg = e.message
        print("Error while {} Details:{}".format(gmsg, emsg))
Example #12
0
    def place_creeps(self, random_y, random_x):
        # Mobs #
        for random_walls in range(rrange(2, 8)):
            mob_pos = [rrange(2, random_y-2), rrange(2, random_x-2)]
            if self.map_grid[mob_pos[0]][mob_pos[1]] not in self.mobs_list:

                spawn = self.get_creeps()
                self.map_grid[mob_pos[0]][mob_pos[1]] = spawn['number']
                self.amount += 1
                self.creeps_alive[self.amount] = {'name': spawn['name'],
                                                  'pos': mob_pos,
                                                  'hp': spawn['HP']}
        print(self.creeps_alive)
Example #13
0
def generate_human_traj(node_traj, mover):

    #human_traj[time, path, 3 dim, 2 points]
    human_traj = np.zeros((len(mover['section']), \
     len(mover['paths']), 3, 2))

    for path_num, path in enumerate(mover['paths']):
        start_point = node_traj[path[0]] + mover['pos']
        end_point = node_traj[path[1]] + mover['pos']
        human_traj[:, path_num, :, 0] = start_point + rrange(-0.01, 0.01)
        human_traj[:, path_num, :, 1] = end_point + rrange(-0.01, 0.01)

    return human_traj
Example #14
0
def insert(cur, db, rowData):
    if db == 'sqlite':
        cur.executemany("INSERT INTO funds VALUES(%s, %s, %s)",
                [(who, uid, rrange(1,5)) for who, uid in randName()])

    elif db == 'gadfly':
        for who, uid in randName():
            cur.execute("INSERT INTO funds VALUES(%s, %s, %s)", 
                    (who, uid, rrange(1, 5)))

    elif db == 'mysql':
       #rowData = (u'879', u'700002', u'\u5e73\u5b89\u5927\u534e\u6df1\u8bc1300', u'0.9580', u'1.0380', u'-2.45%', u'\u5f00\u653e', u'\u5f00\u653e')
       #rowData = ('1','2','2','5','6','7','8','9')
       cur.execute("INSERT INTO funds VALUES(%s, %s, %s, %s, %s, %s, %s, %s)", rowData)
    def search_command(self):

        print('you search the area and find...')
        self.random_items(self.room_temp)
        fate = rrange(1,15)
        if fate >= 8:
            coins = rrange(5,25)
            print('\t{} gold coins!'.format(coins))
            self.gold.append(coins)
            print('\tYou have a total of {} gold coins'.format(sum(self.gold)))
            print('')
        else:
            print('Nothing else of importance..')
        return
Example #16
0
    def __init__(self):
        # GameCommLib.__init__(self)

        self.eq_armor_slots = {'head':    {'name':'','DEF':1,'OFF':0,'ATT':0,'equips':'head','mod':-1},
                               'body':   {'name':'','DEF':3,'OFF':0,'ATT':0,'equips':'body','mod':0},
                               'legs': {'name':'','DEF':1,'OFF':0,'ATT':0,'equips':'legs','mod':0},
                               'lhand':  {'name':'','DEF':1,'OFF':0,'ATT':0,'equips':'left hand','mod':0},
                               'rhand':   {'name':'','DEF':1,'OFF':1,'ATT':1,'equips':'right hand','mod':+1}}

        self.STR = rrange(6,20)
        self.DEX = rrange(6,20)
        self.CON = rrange(6,20)
        self.stats = [self.STR, self.DEX, self.CON]

        self.run = False
Example #17
0
def spawner(targets, stage):
    n_targets = stage + FIRST_STAGE
    if len(targets.sprites()) < n_targets:
        rnum = rrange(100)
        try:
            rmb_prob = RMB_PROB[stage]
        except IndexError:
            rmb_prob = RMB_PROB[len(RMB_PROB)-1]
        if rnum >= rmb_prob:
            buttons = (1, )
        else:
            buttons = (3, )
        Target((rrange(0 + TARGET_RADIUS, 480 - TARGET_RADIUS),
               rrange(0 + TARGET_RADIUS, 480 - TARGET_RADIUS)),
               targets, buttons)
Example #18
0
    def mageMenu(self):
        if self.ai:
            choice = rrange(1, 4)
        else:
            print("1. Cast Fireball (6 mana) "
                  "\n2. Cast Heal (4 mana)"
                  "\n3. Rest... (+4 mana)")
            choice = input("Selection: ")
        if choice:
            choice = int(choice)

        if choice is 1:
            if self.checkmana(6):
                self.castfireball()
                self.mana -= 6
            else:
                print("You are out of mana! Choose another option, I suggest resting...")
                self.mageMenu()
        elif choice is 2:
            if self.checkmana(4):
                if self.gethealth() >= self.maxhealth:
                    print("You're already at max health! Choose again!")
                    self.mageMenu()
                else:
                    self.castheal()
                    self.mana -= 4
            else:
                print("You are out of mana! Choose another option, I suggest resting...")
                self.mageMenu()
        elif choice is 3:
            if self.mana < self.maxmana:
                print("Resting.... ah... so nice... Probably going to get punched a lot. Just saying.")
                self.mana += 4
            else:
                print("Resting, but not going to recover anything... probably should have done something else... ")
        else:
            print("\nBad choice, try again..")

            self.mageMenu()
            if self.ai:
                choice = rrange(1, 4)
            else:
                print("1. Cast Fireball (6 mana) "
                      "\n2. Cast Heal (4 mana)"
                      "\n3. Rest... (+4 mana)")
                choice = input("Selection: ")
            if choice:
                choice = int(choice)
Example #19
0
 def random_treasure(self):
     gold = rrange(10, 50)
     self.messages.append([("You found {} pieces of gold!".format(gold)), self.YELLOW])
     print(">>", self.messages[0][0], self.messages[0][1])
     self.player_gold = gold + self.player_gold
     self.player_info_area()
     self.info_area(self.messages[0][0], self.messages[0][1])
Example #20
0
 def __init__(self, stat: Perf):
     self._id = stat.userId + ":" + str(stat.perfType)
     self.perf = stat.perfType
     self.rating = stat.r
     self.progress = stat.r + rrange(-40, 40)
     self.stable = True
     self.expiresAt = datetime.datetime.now() + datetime.timedelta(days=10)
Example #21
0
    def __init__(self, u: User):
        self._id = u._id
        if not hasattr(u, "perfs"):
            return
        for (name, perf) in u.perfs.items():

            newR = u.perfs[name]["gl"]["r"]
            origR = min(3000, max(400, rrange(
                newR - 500, newR + 500)))  # used to be sooo much better/worse!

            self.__dict__[name] = {}
            days: int = (datetime.datetime.now() - u.createdAt).days
            for x in range(0, days, rrange(2, 10)):
                intermediateR = int(origR + (newR - origR) * x / max(days, 1))
                self.__dict__[name][str(x)] = rrange(intermediateR - 100,
                                                     intermediateR + 100)
Example #22
0
    def __init__(self):

        super(self.__class__, self).__init__(800, 685, "Colour Sort")
        self.color(fl_rgb_color(34, 34, 34))
        self.begin()

        self.buttons = []
        for y in xrange(18):
            hsl_values = range(y * 20, y * 20 + 20)
            for x in xrange(20):

                but = Fl_Button(x * 35 + 30, y * 35 + 30, 30, 30)

                if x == 0 or x == 19:
                    curr_color = hsl_values.pop(0)
                    boxtype = FL_FLAT_BOX
                else:
                    curr_color = hsl_values.pop(rrange(0, len(hsl_values) - 1))
                    boxtype = FL_DOWN_BOX
                    but.callback(self.swap, (x, y))

                bcolor = fl_rgb_color(*self.hsl_rgb(curr_color, 0.5, 0.5))
                but.color(bcolor)
                but.box(boxtype)
                self.buttons.append([but, (x, y), curr_color])

        check_but = Fl_Button(740, 30, 50, 30, "Check")
        check_but.color(fl_rgb_color(80, 160, 0), fl_rgb_color(80, 160, 0))
        check_but.callback(self.check)

        self.selected = []

        self.end()
        self.show()
Example #23
0
def create_setup():
    resume_game = False
    statedict = {
        "Testno.": rrange(1, 10),
        "Choice": [1, 2, 3, 4, 5, 6, 7, 8, 9],
        "Score": 0,
        "Refresh": 5
    }
    start_game(resume_game, statedict)
Example #24
0
 def __init__(self, uid: str):
     self._id = gen.nextId(UBlogPost)
     self.blog = f"user:{uid}"
     self.title = gen.randomTopic()
     self.intro = gen.randomTopic()
     self.markdown = (
         f"![image]({gen.randomImageLink()})\n{gen.randomParagraph()}\n"
         f"![image]({gen.randomImageLink()})\n{gen.randomParagraph()}\n"
         f"![image]({gen.randomImageLink()})\n{gen.randomParagraph()}")
     self.language = "en-US"
     self.live = True
     self.topics = random.sample(_blogTopics, 3)
     self.created = {"by": uid, "at": util.timeSinceDaysAgo(365)}
     self.lived = self.created
     self.updated = self.created
     self.rank = self.created["at"] - timedelta(days=30)  # wtf is this?
     self.views = rrange(10, 100)
     self.likes = rrange(3, 10)
     self.likers = random.sample(gen.uids, self.likes)
Example #25
0
 def __init__(self, pos, group, type, frame = False):
     pg.sprite.Sprite.__init__(self, group)
     if   type == 1:
         if not frame:
             image = self.lmb_images[rrange(5)].convert()
         else:
             image = self.lmb_frame[rrange(5)].convert()
     elif type == 3:
         if not frame:
             image = self.rmb_images[rrange(5)].convert()
         else:
             image = self.rmb_frame[rrange(5)].convert()
     self.image = image
     self.rect  = image.get_rect()
     self.rect.center = pos
     self.veloc = uniform(-0.5, 0.5), uniform(-0.5, 0.5)
     self.pos   = pos
     self.timer = 20
     self.alpha = 255
Example #26
0
 def warriorMenu(self):
     if self.ai:
         choice = rrange(1, 4)
     else:
         print("1. Attack with Sword (No Mana) "
               "\n2. Power Attack (3 mana)"
               "\n3. Rest... (+2 mana)")
         choice = input("Selection: ")
     if choice:
         choice = int(choice)
     if choice is 1:
Example #27
0
 def __init__(self, name: str):
     self._id = util.normalizeId(name)
     self.name = name
     self.description = gen.randomTopic()
     self.descPrivate = "All of our dads could beat up YOUR dad."
     self.nbMembers = 1
     self.enabled = True
     self.open = util.chance(0.5)
     self.createdAt = util.timeSinceDaysAgo(1440)
     self.leaders = list(random.sample(gen.uids, (rrange(1, 4))))
     self.createdBy = self.leaders[0]
     self.chat = 20  # of course chat and forum are equal to 20.
     self.forum = 20  # wtf else would they possibly be??
Example #28
0
    def creeps_attack(self, check_pos):
        self.check_pos = check_pos

        print('check pos(Creeps Attack)', check_pos)
        for each in self.creeps_alive:
            if check_pos[0] == self.creeps_alive[each]['pos'][0] and \
               check_pos[1] == self.creeps_alive[each]['pos'][1]:
                    self.stats = self.creeps_dict[self.creeps_alive[each]['name']]
                    self.spawn = self.creeps_alive[each]
                    spawn_dmg = rrange(1, self.stats['DMG'])
                    if rrange(self.stats['DMG']) != 0:
                        self.messages = []
                        self.messages.append([('A {} attacks you.. with its {}'.format(self.stats['name'], self.stats['weapon'])),self.RED])
                        self.messages.append([('Doing {} points of damage'.format(spawn_dmg)),self.YELLOW])

                        # self.info_area(['A {} attacks you.. with its {}'.format(self.stats['name'], self.stats['weapon']),
                        #                 ('Doing {} points of damage'.format(spawn_dmg))], self.RED)

                        print('A {} attacks you.. with its {}'.format(self.stats['name'], self.stats['weapon']))
                        print('Doing {} points of damage'.format(spawn_dmg))

                        self.player_HP = self.player_HP - spawn_dmg
                        self.player_info_area()
                        self.hp = self.player_attack(self.spawn['name'], self.spawn['hp'], self.stats['DEF'])
                        self.spawn['hp'] = self.hp
                        print('Creeps_attack Function HP', self.hp)
                        return self.hp
                    else:
                        self.messages = []
                        self.messages.append(['A {} attacks you.. with its {}'.format(self.spawn['name'], self.stats['weapon']),self.RED])
                        self.messages.append([('But fails to do any damage!'),self.YELLOW])
                        # self.info_area(['A {} attacks you.. with its {}'.format(self.spawn['name'], self.stats['weapon']),
                        #                 'But fails to do any damage!'], self.WHITE)
                        print('Creature fails in attack!!')
                        self.player_info_area()
                        self.hp = self.player_attack(self.spawn['name'], self.spawn['hp'], self.stats['DEF'])
                        self.spawn['hp'] = self.hp
                        print('Creeps_attack Function HP', self.hp)
                        return self.hp
Example #29
0
 def play2(self):
     print("")
     sm = choice([True,False])
     if sm ==True:
         self.AI(0,1,2)
         self.AI(3,4,5)
         self.AI(6,7,8)
         self.AI(0,3,6)
         self.AI(1,4,7)
         self.AI(2,5,8)
         self.AI(2,4,6)
         self.AI(0,4,8)
         self.AI(6,4,2)
         self.AI(8,4,0)
         self.AI(5,4,3)
         self.AI(2,1,0)
         self.AI(8,7,6)
     else:
         cpu = rrange(0,9)
         if self.map[cpu] not in ['X','O']:
             self.map[cpu] = self.p2
             print("COM picked ",cpu)
             self.done = True
     while self.done !=True:
         cpu = rrange(0,9)
         if self.map[cpu] not in ['X','O']:
             self.map[cpu] = self.p2
             print("COM picked ",cpu)
             self.done =True
     self.check_map(0,1,2)
     self.check_map(3,4,5)
     self.check_map(6,7,8)
     self.check_map(0,3,6)
     self.check_map(1,4,7)
     self.check_map(2,5,8)
     self.check_map(0,4,8)
     self.check_map(2,4,6)
     self.count +=1
Example #30
0
 def play2(self):
     print("")
     sm = choice([True, False])
     if sm == True:
         self.AI(0, 1, 2)
         self.AI(3, 4, 5)
         self.AI(6, 7, 8)
         self.AI(0, 3, 6)
         self.AI(1, 4, 7)
         self.AI(2, 5, 8)
         self.AI(2, 4, 6)
         self.AI(0, 4, 8)
         self.AI(6, 4, 2)
         self.AI(8, 4, 0)
         self.AI(5, 4, 3)
         self.AI(2, 1, 0)
         self.AI(8, 7, 6)
     else:
         cpu = rrange(0, 9)
         if self.map[cpu] not in ['X', 'O']:
             self.map[cpu] = self.p2
             print("COM picked ", cpu)
             self.done = True
     while self.done != True:
         cpu = rrange(0, 9)
         if self.map[cpu] not in ['X', 'O']:
             self.map[cpu] = self.p2
             print("COM picked ", cpu)
             self.done = True
     self.check_map(0, 1, 2)
     self.check_map(3, 4, 5)
     self.check_map(6, 7, 8)
     self.check_map(0, 3, 6)
     self.check_map(1, 4, 7)
     self.check_map(2, 5, 8)
     self.check_map(0, 4, 8)
     self.check_map(2, 4, 6)
     self.count += 1
Example #31
0
def test_falling(falling):
    print()
    labels = [
        'standing', 'sitting', 'walking', 'running', 'grabbing', 'inspection',
        'concealing', 'lying_on_floor'
    ]
    engine = SequenceRuleEngine(labels, '->')
    rule = engine.compile(falling)
    logging.info(f"rule={falling}")
    logging.info(f"compiled={rule}")

    for _ in range(10):
        precursor = [labels[rrange(0, len(labels))] for i in range(4)]
        precondition = [labels[rrange(0, 4)]] * rrange(3, 10)
        postcondition = [labels[-1]] * rrange(3, 10)
        postcursor = [labels[rrange(0, len(labels))] for i in range(4)]
        input = precursor + precondition + postcondition + postcursor
        encoded = engine.encode(*input)
        matches = re.findall(rule, encoded)
        logging.info(f"input={input}")
        logging.info(f"encoded={re.compile(encoded)}")
        logging.info(f"matches={matches}")
        assert matches

    for _ in range(10):
        precursor = [labels[rrange(0, len(labels))] for i in range(4)]
        precondition = [labels[rrange(0, 4)]] * rrange(3, 10)
        postcondition = [labels[-1]] * rrange(3, 10)
        postcursor = [labels[rrange(0, len(labels))] for i in range(4)]
        input = precursor + postcursor
        encoded = engine.encode(*input)
        matches = re.findall(rule, encoded)
        logging.info(f"input={input}")
        logging.info(f"encoded={re.compile(encoded)}")
        logging.info(f"matches={matches}")
        assert not matches
Example #32
0
def test_shoplifting(shoplifting):
    print()
    labels = [
        'standing',
        'sitting',
        'walking',
        'running',
        'grabbing',
        'inspection',
        'concealing',
        'lying_on_floor',
        'walking_items',
        'retrieving_items',
        'returning_items',
        'concealing_items',
    ]
    engine = SequenceRuleEngine(labels, '->')
    rule = engine.compile(shoplifting)
    logging.info(f"rule={shoplifting}")
    logging.info(f"compiled={rule}")

    for _ in range(10):
        precursor = [labels[rrange(0, len(labels))] for i in range(4)]
        retrieving_items = ['retrieving_items'] * rrange(2, 5)
        walking_items = ['walking_items'] * rrange(0, 1) + ['walking'
                                                            ] * rrange(0, 1)
        concealing_items = ['concealing_items'] * rrange(2, 5)
        postcursor = [labels[rrange(0, len(labels))] for i in range(4)]
        input = precursor + retrieving_items + walking_items + concealing_items + postcursor
        encoded = engine.encode(*input)
        matches = re.findall(rule, encoded)
        logging.info(f"input={input}")
        logging.info(f"encoded={re.compile(encoded)}")
        logging.info(f"matches={matches}")
        assert matches

    for _ in range(10):
        precursor = [labels[rrange(0, 9)] for i in range(4)]
        postcursor = [labels[rrange(0, 9)] for i in range(4)]
        input = precursor + postcursor
        encoded = engine.encode(*input)
        matches = re.findall(rule, encoded)
        logging.info(f"input={input}")
        logging.info(f"encoded={encoded}")
        logging.info(f"matches={matches}")
        assert not matches
Example #33
0
def insert(dbsel, db):
    if dbsel == 'sqlite':
        db.insert("INSERT INTO %s VALUES(?, ?, ?)" % db.tableName,
                  [(who, uid, rrange(1, 5)) for who, uid in randName()])
    elif dbsel == 'gadfly':
        '''
        for who, uid in randName():
            cur.execute("INSERT INTO users VALUES(?, ?, ?)",
                        (who, uid, rrange(1, 5)))
        '''
        pass
    elif dbsel == 'mysql':
        '''
        cur.executemany("INSERT INTO users VALUES(?, ?, ?)",
        [(who, uid, rrange(1, 5)) for who, uid in randName()])
        '''
        pass
Example #34
0
    def random_items(self, room_temp=dict):
        chance = mt.ceil(rnd.randrange(1, 13))
        if chance > 3:

            item = rrange(0, len(self.items))
            # print('## DEBUG ##  item value = {}'.format(item))
            print("\tyou see a *{}* on the ground".format(self.items[item]))
            # backpack.append(items[item])
            # try:
            if room_temp["room"] in self.room_items.keys():
                # print('## DEBUG ## Try ITEMS',room_items)
                self.room_items[room_temp["room"]]["items"].append(self.items[item])
            # except Exception as inst:
            else:
                # print(inst)
                self.room_items[room_temp["room"]] = {"items": [self.items[item]]}
                # print('## DEBUG ## except ITEMS',room_items)

        return
 def play(self):
     game = True
     s = 0
     print('Please wait...')
     shuffle(self.bank)
     while 'none' in self.bank[s]:
         self.fail +=1
         s = rrange(0,len(self.bank))
     print(self.fail)
     word = self.bank[s]
     f = False
     while game==True:
         print("Life Left: ",self.life)
         f = False
         print('Hint: ',word[1])
         self.display2(word[0])
         letter = input(": ")
         if word[0]==letter:
             print("WOW")
             game = False
         else:
             a = 0
             while a < len(word[0]):
                 if word[0][a]==letter:
                     self.fill_word[a]= letter
                     f = True
                 a +=1
         if f==False:
             self.life -=1
         if self.life < 0:
             game = False
         if '_' not in self.fill_word:
             game = False
     print(word[0])
     print('GAME OVER')
     self.clear()
     self.main()
Example #36
0
 def play(self):
     game = True
     s = 0
     print('Please wait...')
     shuffle(self.bank)
     while 'none' in self.bank[s]:
         self.fail +=1
         s = rrange(0,len(self.bank))
     print(self.fail)
     word = self.bank[s]
     f = False
     while game==True:
         print("Life Left: ",self.life)
         f = False
         print('Hint: ',word[1])
         self.display2(word[0])
         letter = input(": ")
         if word[0]==letter:
             print("WOW")
             game = False
         else:
             a = 0
             while a < len(word[0]):
                 if word[0][a]==letter:
                     self.fill_word[a]= letter
                     f = True
                 a +=1
         if f==False:
             self.life -=1
         if self.life < 0:
             game = False
         if '_' not in self.fill_word:
             game = False
     print(word[0])
     print('GAME OVER')
     self.clear()
     self.main()
Example #37
0
    def create_random_map(self):
        # LAYOUT ROOM ##
        random_x = rrange(7,35)
        random_y = rrange(7,15)
        self.map_grid = [[0 for x in range(random_x)] for y in range(random_y)]
        for pos_x in range(1, len(self.map_grid)-1):
            for pos_y in range(1, len(self.map_grid[pos_x])-1):
                self.map_grid[pos_x][pos_y] = 1

        # DEFINE PLAYER START LOCATION ##
        self.player_pos = [rrange(2, random_y-2), rrange(2, random_x-2)]
        print('MAP:',random_x, random_y)
        print('PLAYER:',self.player_pos)
        self.map_grid[self.player_pos[0]][self.player_pos[1]] = 2

        # CREATE RANDOM ITEMS IN ROOM ##

        # Walls #
        for random_walls in range(rrange(1, 19)):
            wall_pos = [rrange(2, random_y-2), rrange(2, random_x-2)]
            if self.map_grid[wall_pos[0]][wall_pos[1]] != 2:
                self.map_grid[wall_pos[0]][wall_pos[1]] = 0

        return [random_x, random_y]
Example #38
0
 def place_treasure(self, random_y, random_x):
     # TREASURE CHESTS #
     for random_walls in range(rrange(1, 3)):
         mob_pos = [rrange(2, random_y - 2), rrange(2, random_x - 2)]
         if self.map_grid[mob_pos[0]][mob_pos[1]] < 2 > 0:
             self.map_grid[mob_pos[0]][mob_pos[1]] = 7
 def update(self):
     users = self.users
     fr = rrange(1,5)
     to = rrange(1,5)
     return fr, to, \
         users.update(users.c.prid==fr).execute(prid=to).rowcount
 def delete(self):
     users = self.users
     rm = rrange(1,5)
     return rm, \
         users.delete(users.c.prid==rm).execute().rowcount
def randName():
    pick = list(NAMES)
    while len(pick) > 0:
        yield pick.pop(rrange(len(pick)))
 def insert(self):
     d = [dict(zip(FIELDS,
         [who, uid, rrange(1,5)])) for who, uid in randName()]
     return self.users.insert().execute(*d).rowcount
Example #43
0
 def place_npc(self, random_y, random_x):
     # PLACE NPC #
     for random_walls in range(rrange(1, 2)):
         mob_pos = [rrange(2, random_y-2), rrange(2, random_x-2)]
         if self.map_grid[mob_pos[0]][mob_pos[1]] < 2 > 0:
             self.map_grid[mob_pos[0]][mob_pos[1]] = 80
def delete(cur):
    rm = rrange(1,5)
    cur.execute('DELETE FROM users WHERE prid=%d' % rm)
    return rm, getRC(cur)
Example #45
0
def update(cur):
    fr = rrange(1, 5)
    to = rrange(1, 5)
    cur.execute("UPDATE users SET prid=%d WHERE prid=%d" % (to, fr))
    return fr, to, getRC(cur)
Example #46
0
def delete(cur):
    rm = rrange(1, 5)
    cur.execute('DELETE FROM users WHERE prid=%d' % rm)
    return rm, getRC(cur)
Example #47
0
def update(cur):
    fr = rrange(1, 5)
    to = rrange(1, 5)
    cur.execute('update users set prid = %d where prid = %d' (to, fr))
    return fr, to, getRC(cur)
Example #48
0
 def npc_rarity_check(self, random_x, random_y):
     rarity = rrange(1, 100)
     if self.npc_dict['cleric']['rarity'] <= rarity:
         print('Cleric appears..')
         self.place_npc(random_x, random_y)
Example #49
0
 def delete(self):
     users = self.users
     rm = rrange(1, 5)
     return rm, \
            users.delete(users.c.prid == rm).execute().rowcount
Example #50
0
 def update(self):
     users = self.users
     fr = rrange(1, 5)
     to = rrange(1, 5)
     return fr, to, \
            users.update(users.c.prid == fr).execute(prid=to).rowcount
Example #51
0
def delete(cur):
    rm = rrange(1, 5)
    cur.execute('delete from users where prid=%d' % rm)
    return rm, getRC(cur)
Example #52
0
 def insert(self):
     for who, uid in randName():
         self.users(**dict(zip(FIELDS,
             [who, uid, rrange(1,5)])))
def update(cur):
    fr = rrange(1,5)
    to = rrange(1,5)
    cur.execute(
        "UPDATE users SET prid=%d WHERE prid=%d" % (to, fr))
    return fr, to, getRC(cur)
Example #54
0
def randName():
    pick = list(NAMES)
    while len(pick) > 0:
        yield pick.pop(rrange(len(pick)))
Example #55
0
 def delete(self):
     rm = rrange(1,5)
     users = self.users.selectBy(prid=rm)
     for i, user in enumerate(users):
         user.destroySelf()
     return rm, i+1
 def insert(self):
     for who, uid in randName():
         self.users(**dict(zip(FIELDS, [who, uid, rrange(1, 5)])))
Example #57
0
 def randomSocialMediaLinks(self) -> list[str]:
     return random.sample(self.socialMediaLinks, rrange(0, 6))
 def delete(self):
     rm = rrange(1, 5)
     users = self.users.selectBy(prid=rm)
     for i, user in enumerate(users):
         user.destroySelf()
     return rm, i + 1
Example #59
0
 def insert(self):
     d = [
         dict(zip(FIELDS, [who, uid, rrange(1, 5)]))
         for who, uid in randName()
     ]
     return self.users.insert().execute(*d).rowcount