コード例 #1
0
 def effect2(self, speed):
     """Эффект 'Бегущая строка' """
     from urandom import choice
     self.led_effect_status = 1
     colors = [
         0,
         round(128 / 100 * self.led_brightness),
         round(255 / 100 * self.led_brightness)
     ]
     delay = round(0.1 - (0.0009 * speed), 3)
     while self.led_effect:
         col = [choice(colors), choice(colors), choice(colors)]
         for led in range(self.led_pixels):
             black = led - 4
             if black < 0:
                 black = self.led_pixels + black
             self.np[led] = col
             self.np[black] = [0, 0, 0]
             self.np.write()
             sleep(delay)
             if not self.led_effect:
                 break
     else:
         self.np_clear()
         self.led_effect_status = 0
コード例 #2
0
ファイル: ogress.py プロジェクト: yukota/ogress
 def _get_action(self, state, episode):
     eps = 0.9 * (1 / episode * 0.001 + 1)
     if eps < random():
         # suit act
         next_action = self._mlp.QLearningPredictBestActionIndex(state)
         if next_action is None:
             next_action = choice([0, 1, 2])
     else:
         next_action = choice([0, 1, 2])
     return next_action
コード例 #3
0
    def main(f):
        phrases = [
            "It is certain.", "It is decidedly so.", "Without a doubt.",
            "Yes - definitely.", "You may rely on it.", "As I see it, yes.",
            "Most likely.", "Outlook good.", "Yes.", "Signs point to yes.",
            "Reply hazy, try again", "Ask again later.",
            "Better not tell you now.", "Cannot predict now.",
            "Concentrate and ask again.", "Don't count on it.",
            "My reply is no.", "My sources say no.", "Outlook not so good.",
            "Very doubtful."
        ]
        i2c = machine.I2C(scl=Pin(22), sda=Pin(21))
        epd.init()
        epd.set_rotate(gxgde0213b1.ROTATE_270)
        epd.clear_frame(fb)
        epd.display_frame(fb)
        prev_orientation = None

        keep_on = [True]

        def exit_loop():
            keep_on[0] = False

        exit_button = TouchButton(Pin(32), exit_loop)

        while keep_on[0]:
            exit_button.read()
            orientation = MagicBall.get_orientation(i2c)

            if orientation and orientation != prev_orientation:
                if orientation == 'upright':
                    MagicBall.show_message(urandom.choice(phrases))
                elif orientation == 'prone':
                    MagicBall.clear_screen()
            prev_orientation = orientation
コード例 #4
0
ファイル: main.py プロジェクト: bbk012/uPyBot
 def rnd_turn(
     self, move_result
 ):  #make rundom turn of random type but only if not an obstacle detected for which 90 deg turn is executed always
     turn_type = random.choice(
         [uPyBot.SYMMETRIC_TURN, uPyBot.ASYMMETRIC_TURN])
     turn_direction = random.choice([uPyBot.LEFT_TURN, uPyBot.RIGHT_TURN])
     turn_angle = random.choice([uPyBot.TURN_90, uPyBot.TURN_180])
     wheel_turn_angle = random.choice(
         [uPyBot.WHEEL_TURN_90, uPyBot.WHEEL_TURN_180])
     if move_result != uPyBot.MOVE_OK:
         self.symmetric_turn(turn_direction, uPyBot.TURN_90)
     else:
         if turn_type == uPyBot.SYMMETRIC_TURN:
             self.symmetric_turn(turn_direction, turn_angle)
         else:
             self.asymmetric_turn(turn_direction, wheel_turn_angle)
コード例 #5
0
def play_all_files_random_order():
    files = os.listdir('.')
    # print(files)
    file = choice(files)
    if (file[-4:] == '.blm'):
        #vibra.vibrate(60)
        render_error('file:', file[:-4])
        play_blinken_blm_file(file)
コード例 #6
0
def random_string(length=8):
    #Generate a random string of fixed length
    _randomstring = ''
    x = 0
    #add random seed seconds of localtime
    seed(localtime()[5])
    while x < length:
        _randomstring = _randomstring + choice(
            'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890')
        x += 1
    return _randomstring
コード例 #7
0
def CreatRandomPhoneNum(count=8):
    pre_lst = [
        "130", "131", "132", "133", "134", "135", "136", "137", "138", "139",
        "147", "150", "151", "152", "153", "155", "156", "157", "158", "159",
        "186", "187", "188"
    ]
    # 生成8个随机数个位数
    tail_str = [str(random.randint(0, 9)) for i in range(count)]
    # 将其转化为字符串
    tail_str = ''.join(tail_str)
    return random.choice(pre_lst) + tail_str
    pass
コード例 #8
0
 def effect3(self, speed):
     """Эффект 'Появление' """
     self.led_effect_status = 1
     from urandom import randint, choice
     delay = round((0.2 - (speed * 0.0015)), 3)
     colors = [
         0,
         round(128 / 100 * self.led_brightness),
         round(255 / 100 * self.led_brightness)
     ]
     step = max(1, round(colors[2] / 100 * 2))
     while self.led_effect:
         col = [choice(colors), choice(colors), choice(colors)]
         leds = list(range(self.led_pixels))
         while leds:
             led = randint(0, len(leds) - 1)
             self.np[leds[led]] = col
             self.np.write()
             del leds[led]
             sleep(delay)
             if not self.led_effect:
                 break
         while True:
             if sum(col):
                 if not self.led_effect:
                     break
                 for i in range(3):
                     if col[i] > 0:
                         col[i] = max(0, col[i] - step)
                 sleep(0.01)
                 self.np.fill(col)
                 self.np.write()
             else:
                 break
         sleep(0.5)
     else:
         self.np_clear()
         self.led_effect_status = 0
コード例 #9
0
    def random_single(self, delay, duration, random_delay=False):
        """
        Turn on and off a single LED randomly

        Args:
            delay (int): the delay in milliseconds between two LED being
            lighted
            duration (int): for how long (in milliseconds) the method will run
            random_delay (bool): if True it will overwrite the delay for a new
                delay between 0 and the passed delay
        """
        until = pyb.millis() + duration

        while (pyb.millis() < until):
            if (random_delay):
                delay = urandom.randint(0, delay)
            led = urandom.choice(self.__leds)
            led.on()
            pyb.delay(delay)
            led.off()
        self.all_off()
コード例 #10
0
def init(pattern):
    # draw pattern and wait a few seconds before the next step
    draw_pattern(pattern)
    time.sleep(3)

    # shuffle and draw current_lights, kind of DIY solution
    current_lights = {}

    # represents the original pattern, this handles gaps
    options = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]

    for i in range(16):
        # pick an option
        pick = urandom.choice(options)

        # use that value from the original pattern, remove this from the options
        if pick in pattern:
            current_lights[i] = pattern[pick]

        options.remove(pick)

    draw_pattern(current_lights)
    return current_lights
コード例 #11
0
ファイル: table.py プロジェクト: genjix/kartludox
    def start(self):
        """Start the game."""
        if self.game_state != GameState.STARTING:
            if self.game_state == GameState.RUNNING:
                print('Game already running.')
            else:
                print('Start game cancelled.')
            return
        self.game_state = GameState.RUNNING
        print('Game started.')
        # select a random dealer
        occupied_seats = \
            [i for i, p in enumerate(self.seats) if p and not p.sitting_out]
        self.dealer = random.choice(occupied_seats)

        # Let everyone off paying for the first hand!
        # (Except the blinds)
        for player in self.seats:
            if player is not None and not player.sitting_out:
                player.paid_state = player.PAID_SB_BB
        # Start the actual game
        scr = script.Script(self)
        if self.handler:
            self.handler.start(scr)
コード例 #12
0
ファイル: table.py プロジェクト: embicoin/kartludox
    def start(self):
        """Start the game."""
        if self.game_state != GameState.STARTING:
            if self.game_state == GameState.RUNNING:
                print('Game already running.')
            else:
                print('Start game cancelled.')
            return
        self.game_state = GameState.RUNNING
        print('Game started.')
        # select a random dealer
        occupied_seats = \
            [i for i, p in enumerate(self.seats) if p and not p.sitting_out]
        self.dealer = random.choice(occupied_seats)

        # Let everyone off paying for the first hand!
        # (Except the blinds)
        for player in self.seats:
            if player is not None and not player.sitting_out:
                player.paid_state = player.PAID_SB_BB
        # Start the actual game
        scr = script.Script(self)
        if self.handler:
            self.handler.start(scr)
コード例 #13
0
print('randint')
for i in range(50):
    assert 0 <= random.randint(0, 4) <= 4
    assert 2 <= random.randint(2, 6) <= 6
    assert -2 <= random.randint(-2, 2) <= 2

# empty range
try:
    random.randint(2, 1)
except ValueError:
    print('ValueError')

print('choice')
lst = [1, 2, 5, 6]
for i in range(50):
    assert random.choice(lst) in lst

# empty sequence
try:
    random.choice([])
except IndexError:
    print('IndexError')

print('random')
for i in range(50):
    assert 0 <= random.random() < 1

print('uniform')
for i in range(50):
    assert 0 <= random.uniform(0, 4) <= 4
    assert 2 <= random.uniform(2, 6) <= 6
コード例 #14
0
ファイル: explore.py プロジェクト: Furrane/pybstick-projects
sw = Switch()

# Wait user A to be pressed
while not sw.value():
    sleep(0.100)

# wait 10 secondes before start
for i in range(9):
    LED(1).on()
    sleep(0.100)
    LED(1).off()
    sleep(1)
# Final indicator
LED(1).on()
sleep(1)
LED(1).off()

try:
    while True:
        # if object detected
        while sr04.distance_in_cm() <= 25:
            # turn on right (positive speed) or left (negative speed) during a
            # random amount of time (400ms to 1.5s) to find an escape.
            zumo.right(speed=choice([-50, +50]), time_ms=randint(400, 1500))
        if not zumo.is_moving:
            zumo.speed(80)  # Move forward @ speed
        if sw.value():
            break
finally:
    zumo.stop()
コード例 #15
0
def random_filename(N=6):
    #TODO this isn't returning a random name....
    filename = ''.join(urandom.choice('ABCDEFG1234567890') for _ in range(N))
    return filename + '.data'
コード例 #16
0
ファイル: __init__.py プロジェクト: oxzi/badgeapps
def matrix_leds():
    for l in range(15):
        leds.set(l, urandom.choice(COLORS))
コード例 #17
0
ファイル: __init__.py プロジェクト: oxzi/badgeapps
    def update_check(self):
        self._y += self._speed
        self._elems.append(urandom.choice(COLORS))

        return self._y < 80
コード例 #18
0
def flicker(np,
            config,
            strip_number,
            strip_data,
            compressedOutput,
            solid=False):

    animation_data = strip_data["animations"][
        strip_data["animation_index"]]["animation_data"]

    if "flickerCompleted" in animation_data:
        strip_data["done"] = True
        #intColor = animation_data["flickerColor"]
        #np.buf[animation_data["offset"] : animation_data["offset"] + 5] = struct.pack(">HBBB", animation_data["totalLength"], intColor[2], intColor[1], intColor[0])
    else:
        if "flickerPhaseCompleted" in animation_data and animation_data[
                "flickerPhaseCompleted"] or not "flickerPhaseCompleted" in animation_data:
            if "flickerAll" in animation_data and animation_data["flickerAll"]:
                if "flickerPhaseCompleted" in animation_data and animation_data[
                        "flickerPhaseCompleted"]:
                    animation_data["flickerCompleted"] = True
                animation_data["flickerPhaseCompleted"] = False
                animation_data["flickerPhases"] = [
                    (0, 0) for _ in range(0, random.randint(7, 19))
                ]
            else:
                animation_data["flickerPhaseCompleted"] = False
                if not "flickered" in animation_data:
                    animation_data["flickered"] = []
                if "flickerStrip" in animation_data:
                    animation_data["flickered"].append(
                        animation_data["flickerStrip"])
                    del animation_data["flickerStrip"]
                strips = range(0, strip_data["zoneLength"])
                leftStrips = [
                    k for k in strips if k not in animation_data["flickered"]
                ]
                if leftStrips == []:
                    animation_data["flickerCompleted"] = True
                    animation_data["color"] = animation_data["flickerEndColor"]
                else:
                    animation_data["flickerStrip"] = random.choice(leftStrips)

                animation_data["flickerPhases"] = [
                    (random.choice([k for k in range(0, 2)] +
                                   [k for k in range(0, 2)] +
                                   [k for k in range(0, 2)]), 0)
                    for _ in range(0, random.randint(2, 5))
                ]

            animation_data["flickerPhase"] = 0
            animation_data["flickerToggle"] = 0
            animation_data["flickerStep"] = 0
        else:
            animation_data["flickerStep"] += 1
            if animation_data["flickerStep"] > animation_data["flickerPhases"][
                    animation_data["flickerPhase"]][
                        animation_data["flickerToggle"]]:
                animation_data["flickerStep"] = 0
                animation_data["flickerToggle"] += 1
                if animation_data["flickerToggle"] > 1:
                    animation_data["flickerToggle"] = 0
                    animation_data["flickerPhase"] += 1
                    if animation_data["flickerPhase"] >= len(
                            animation_data["flickerPhases"]):
                        animation_data["flickerPhaseCompleted"] = True

        if "flickerAll" in animation_data and animation_data["flickerAll"]:
            colorTo = animation_data["flickerColor"] if animation_data[
                "flickerToggle"] == 1 else [0, 0, 0]

            # TODO: Fix offfset
            #np.buf[strip_data["offset"] + (strip * 5) : strip_data["offset"] + (strip * 5) + 5] = struct.pack(">HBBB", strip_data["stripLength"], colorTo[1], colorTo[0], colorTo[2])
            np.buf[np.currentOffset:np.currentOffset + 5] = struct.pack(
                ">HBBB", strip_data["stripLength"] * strip_data["zoneLength"],
                colorTo[1], colorTo[0], colorTo[2])
            np.currentOffset += 5
        else:
            for strip in range(0, strip_data["zoneLength"]):
                if strip in animation_data["flickered"]:
                    colorTo = animation_data["flickerEndColor"]
                elif strip == animation_data["flickerStrip"]:
                    colorTo = animation_data["flickerColor"] if animation_data[
                        "flickerToggle"] == 1 else [0, 0, 0]
                else:
                    colorTo = animation_data["flickerStartColor"]

                # TODO: Fix offfset
                #np.buf[strip_data["offset"] + (strip * 5) : strip_data["offset"] + (strip * 5) + 5] = struct.pack(">HBBB", strip_data["stripLength"], colorTo[1], colorTo[0], colorTo[2])
                np.buf[np.currentOffset:np.currentOffset + 5] = struct.pack(
                    ">HBBB", strip_data["stripLength"], colorTo[1], colorTo[0],
                    colorTo[2])
                np.currentOffset += 5
コード例 #19
0
nick = 'sample text'
try:
    with open('/nickname.txt') as f:
        nick = f.read()
except:
    pass

while True:
    with display.open() as d:
        for k in range(4):
            (x1, y1) = (randrange(159), randrange(79))
            (x2, y2) = (min(x1 + randrange(40),
                            159), min(y1 + randrange(40), 79))
            try:
                d.rect(x1, y1, x2, y2, col=choice(disp_colors), filled=True)
            except:
                pass
        fg = choice(disp_colors)
        nx = 80 - round(len(nick) / 2 * 14)
        d.print(nick,
                fg=fg,
                bg=[0xff - c for c in fg],
                posx=(nx - 8) + randrange(16),
                posy=22 + randrange(16))
        d.update()
        d.close()
    leds.set(randrange(11), choice(led_colors))
    leds.set_rocket(randrange(3), randrange(32))
    utime.sleep(0.001)
コード例 #20
0
ファイル: __init__.py プロジェクト: oxzi/badgeapps
 def draw(self, disp):
     msg = self._text()
     disp.print(msg,
                fg=urandom.choice(COLORS),
                posx=80 - round(len(msg) / 2 * 14),
                posy=30)
コード例 #21
0
    num = random.randint(1, 4)
    random_log.info(num)

    # random between 0~1
    num = random.random()
    random_log.info(num)

    # urandom.unifrom(start, end)
    # 在开始和结束之间生成浮点数
    num = random.uniform(2, 4)
    random_log.info(num)

    # urandom.randrange(start, end, step)
    # 2-bit binary,the range is [00~11] (0~3)
    num = random.getrandbits(2)
    random_log.info(num)

    # 8-bit binary,the range is [0000 0000~1111 11111] (0~255)
    num = random.getrandbits(8)
    random_log.info(num)

    # urandom.randrange(start, end, step)
    # 从开始到结束随机生成递增的正整数
    num = random.randrange(2, 8, 2)
    random_log.info(num)

    # urandom.choice(obj)
    # 随机生成对象中元素的数量
    num = random.choice("QuecPython")
    random_log.info(num)
コード例 #22
0
ファイル: magic8ball.py プロジェクト: pdp7/ohs18apps
#
# photo gallery:
# https://photos.app.goo.gl/f1y8PSHfYAaa4xTu7
#
# transfer to Open Hardware Summit badge using FTP:
# https://oshwabadge2018.github.io/docs.html#uploading-over-ftp

import gxgde0213b1
import font16
import font12
import urandom
import time

phrases = [
    "It is certain.", "It is decidedly so.", "Without a doubt.",
    "Yes - definitely.", "You may rely on it.", "As I see it, yes.",
    "Most likely.", "Outlook good.", "Yes.", "Signs point to yes.",
    "Reply hazy, try again", "Ask again later.", "Better not tell you now.",
    "Cannot predict now.", "Concentrate and ask again.", "Don't count on it.",
    "My reply is no.", "My sources say no.", "Outlook not so good.",
    "Very doubtful."
]

epd.clear_frame(fb)
epd.set_rotate(gxgde0213b1.ROTATE_270)
epd.clear_frame(fb)
epd.display_string_at(fb, 0, 60, urandom.choice(phrases), font16,
                      gxgde0213b1.COLORED)
epd.display_frame(fb)
time.sleep(2)
コード例 #23
0
def getRandomString(size):
    import urandom
    printableCharacters = 'abcdefghijklmnopqrstuvwxyz1234567890ABCBEFHIJKLMNOPQRSTUVWXYZ'
    return ''.join(urandom.choice(printableCharacters) for x in range(size))
コード例 #24
0
ファイル: main.py プロジェクト: piannone/pybricks-projects
def update_action():
    arm_motor.reset_angle(0)
    action_timer.reset()

    # Drive forward for 4 seconds to leave stand, then stop.
    yield FORWARD_SLOW
    while action_timer.time() < 4000:
        yield

    action = STOP
    yield action

    # Start checking sensors on arms. When specific conditions are sensed,
    # different actions will be performed.
    while True:
        # First, we check the color sensor. The detected color is looked up in
        # the action map.
        new_action = ACTION_MAP.get(color_sensor.color())

        # If the color was found, beep for 0.1 seconds and then change the
        # action depending on which color was detected.
        if new_action is not None:
            action_timer.reset()
            ev3.speaker.beep(1000, -1)
            while action_timer.time() < 100:
                yield
            ev3.speaker.beep(0, -1)

            # If the new action involves steering, combine the new steering
            # with the old drive speed. Otherwise, use the entire new action.
            if new_action.steering != 0:
                action = Action(drive_speed=action.drive_speed,
                                steering=new_action.steering)
            else:
                action = new_action
            yield action

        # If the measured distance of the ultrasonic sensor is less than 250
        # millimeters, then back up slowly.
        if ultrasonic_sensor.distance() < 250:
            # Back up slowly while wiggling the arms back and forth.
            yield BACKWARD_SLOW

            arm_motor.run_angle(ARM_MOTOR_SPEED, 30, wait=False)
            while not arm_motor.control.done():
                yield
            arm_motor.run_angle(ARM_MOTOR_SPEED, -60, wait=False)
            while not arm_motor.control.done():
                yield
            arm_motor.run_angle(ARM_MOTOR_SPEED, 30, wait=False)
            while not arm_motor.control.done():
                yield

            # Randomly turn left or right for 4 seconds while still backing
            # up slowly.
            turn = urandom.choice([TURN_LEFT, TURN_RIGHT])
            yield Action(drive_speed=BACKWARD_SLOW.drive_speed,
                         steering=turn.steering)
            action_timer.reset()
            while action_timer.time() < 4000:
                yield

            # Beep and then restore the previous action from before the
            # ultrasonic sensor detected an obstruction.
            action_timer.reset()
            ev3.speaker.beep(1000, -1)
            while action_timer.time() < 100:
                yield
            ev3.speaker.beep(0, -1)

            yield action

        # This adds a small delay since we don't need to read these sensors
        # continuously. Reading once every 100 milliseconds is fast enough.
        action_timer.reset()
        while action_timer.time() < 100:
            yield
コード例 #25
0
    def __init__(self):

        temp1 = 0
        temp2 = 0
        '''generate question'''
        while temp1 not in numbers:
            temp1 = urandom.randrange(1, 12)

        while temp2 not in numbers:
            temp2 = urandom.randrange(1, 12)

        self.question1 = temp1
        self.question2 = temp2
        '''generate answer'''

        #real answer
        self.answer_real = temp1 * temp2

        #anwer_2
        temp = 0

        while temp == 0 or temp == self.answer_real:
            temp = urandom.randrange(1, 12) * urandom.randrange(1, 12)

        self.answer_2 = temp

        #answer_3

        temp = 0

        while temp == 0 or temp == self.answer_2 or temp == self.answer_real:
            temp = urandom.randrange(1, 12) * urandom.randrange(1, 12)

        self.answer_3 = temp

        #answer_4

        temp = 0

        while temp == 0 or temp == self.answer_3 or temp == self.answer_2 or temp == self.answer_real:
            temp = urandom.randrange(1, 12) * urandom.randrange(1, 12)

        self.answer_4 = temp

        print("q1 : {}".format(self.question1))
        print("q2 : {}".format(self.question2))
        print("ar : {}".format(self.answer_real))
        print("a2 : {}".format(self.answer_2))
        print("a3 : {}".format(self.answer_3))
        print("a4 : {}".format(self.answer_4))

        self.list = [
            self.answer_real, self.answer_2, self.answer_3, self.answer_4
        ]
        self.randomlist = []

        while len(self.randomlist) != 4:
            temp = urandom.choice(self.list)
            if temp not in self.randomlist:
                self.randomlist.append(temp)

        print(self.randomlist)