示例#1
0
def fade(time):
    for x in range(0, 5):
        for y in range(0, 5):
            b = display.get_pixel(x, y)
            if b > 0:
                display.set_pixel(x, y, b - 1)
            sleep(time)
def RadioReceived(text):
    global ball
    global prevBallMove
    global lookingForGame
    print("Received: " + text)
    if(not gameStarted and lookingForGame):
        if(text == "s"):
            ball = Ball(random.randint(0, 4), 0, random.choice([-1, 1]), 1)
            StartCountdown()
        elif(text == "q"):
            radio.send("s")
            ball = None
            StartCountdown()
    else:
        if(text == "w"):
            EndScreen(True)
        elif(text == "l"):
            EndScreen(False)
        elif(text == "p"):
            AddPoint()
            ball = Ball(random.randint(0, 4), 0, random.choice([-1, 1]), 1)
            display.set_pixel(ball.x, ball.y, 9)
            CheckBounce()
            prevBallMove = time.ticks_ms()
        else:
            args = text.split(",")
            if(len(args) == 2):
                ball = Ball(int(args[0]), 0, int(args[1]), 1)
                display.set_pixel(ball.x, ball.y, 9)
                CheckBounce()
                prevBallMove = time.ticks_ms()
示例#3
0
def fade_display(fade=-3):
    """Loop over every pixel and reduce the brightness by the fade value."""
    for x in range(0, 5):
        for y in range(0, 5):
            current = display.get_pixel(x, y)
            faded = max(0, current + fade)
            display.set_pixel(x, y, faded)
示例#4
0
def scan(level, pause=500):
    # Mark reverse as global so we can update it from this method
    global reverse

    # Loop through the various rows of our square. As we're going diagonally we need to loop
    # 9 times.
    for i in range(0, 5):

        # Start looping over the pixel grid
        for x in range(0, 5):

            # if we press a button reverse the direction
            if button_a.is_pressed() or button_b.is_pressed():
                reverse = False if reverse else True

            for y in range(0, i + 1):

                # If the pixel we're trying to set wouldn't be on the grid
                # then don't try and set it
                if x <= MAX_ROWS and y <= MAX_ROWS:
                    x_coord = MAX_ROWS - x if reverse else x
                    y_coord = MAX_ROWS - y if reverse else y

                    display.set_pixel(x_coord, y_coord, level)

        i += 1
        sleep(pause)
示例#5
0
def show(present):
    for x in range(5):
        for y in range(5):
            if present[x][y] == 1:
                display.set_pixel(x, y, 9)
            else:
                display.set_pixel(x, y, 0)
def plotBarGraph(value, max_value, b=9):
    order = (
        23,
        21,
        20,
        22,
        24,
        18,
        16,
        15,
        17,
        19,
        13,
        11,
        10,
        12,
        14,
        8,
        6,
        5,
        7,
        9,
        3,
        1,
        0,
        2,
        4,
    )
    counter = 0
    display.clear()
    for y in range(5):
        for x in range(5):
            if value / max_value > order[counter] / 25:
                display.set_pixel(x, y, b)
            counter += 1
示例#7
0
def count_down(delay):
    """Count down and show progress"""
    on_image = Image('99999:99999:99999:99999:99999')
    display.show(on_image)

    for y_coord in range(5):
        for x_coord in range(5):
            wait = delay
            while wait >= 300:
                sleep(300)
                wait -= 300
                if abandon_talk() is True:
                    return

                # Flash the last row, so making it clear that
                # the talk is coming to an end

                if y_coord == 4:
                    for i in range(x_coord, 5):
                        brightness = display.get_pixel(i, y_coord)
                        if brightness == 0:
                            brightness = 9
                        else:
                            brightness = 0
                        display.set_pixel(i, y_coord, brightness)

            sleep(wait)
            display.set_pixel(x_coord, y_coord, 0)

    start_up_screen()
    return
示例#8
0
def main():
    data_sent = 0
    state = GET_DATA_NUM
    while True:
        # State 0
        if state == GET_DATA_NUM:
            data_num = 1
            attempt = 0
            while True:
                cy, cx = divmod(data_num-1, 5)                          # Cursor x and y depending on the data_num
                display.set_pixel(cx, cy, 9)
                if button_a.is_pressed() and button_b.is_pressed():
                    state = READY_TO_SAMPLE                                        # TODO: Change state to some other state
                    data_sent = 0
                    sleep(500)
                    break
                elif button_a.is_pressed():
                    if data_num > 1:
                        display.set_pixel(cx, cy, 0)                                # Clear LED pixel if data_num > 1
                    data_num = data_num - 1 if (data_num > 1) else 1
                elif button_b.is_pressed():
                    data_num = data_num + 1 if (data_num < MAX_FILES_NUM) else MAX_FILES_NUM
                sleep(200)
        # State 1
        elif state == READY_TO_SAMPLE:
            while True:
                if button_a.is_pressed():
                    state = SAMPLE_DATA
                    break
                elif button_b.is_pressed():
                    display.clear()
                    cy, cx = divmod(data_num-data_sent-1, 5)
                    setPixelTill(cx, cy, 9)
                else:
                    display.show(Image.ARROW_W)
                sleep(200)
        # State 2
        elif state == SAMPLE_DATA:
            countdown(3)
            display.show(Image.TARGET)
            with open("file_{}.csv".format(data_sent), "w") as data_file:
                data_file.write("x,y,z\n")
                initial_time = running_time()
                while (running_time()-initial_time) < SAMPLE_DURATION:
                    t0 = running_time()
                    data_file.write("{},{},{}\n".format(*accelerometer.get_values()))
                    t_diff = running_time()-t0
                    sleep(0 if (SAMPLE_PERIOD-t_diff)<0 else SAMPLE_PERIOD-t_diff)
            data_sent += 1
            if (data_num-data_sent)>0:
                state = READY_TO_SAMPLE
            else:
                state = EXIT
        # State 3
        elif state == EXIT:
            display.show(Image.HAPPY)
            break
示例#9
0
 def update(self):
     # Move enemy down screen
     display.set_pixel(self.x, self.y, 0)
     self.y = self.y + 1
     # Move back to top once off the bottom
     # TODO we should have a delay here
     if self.y >= 5:
         self.x = randint(1, 3)
         self.y = 0
     display.set_pixel(self.x, self.y, 9)
def imp_lista(lista: list, isDificil: bool) -> None:
    display.clear()

    if isDificil:
        fator = 6
    else:
        fator = 1.5

    for y, x in enumerate(lista):
        if (0 <= x < 5 and 0 <= y < 5):
            display.set_pixel(x, y, 9 - int(y * fator))
示例#11
0
def dataWrite(db=databyte, ledrow=3):
    #global databyte
    p = 0
    bright = 6 + ledrow
    for y in range(ledrow, ledrow + 2):
        for x in range(1, 5):
            if db[p] == "1":
                display.set_pixel(x, y, bright)
            else:
                display.set_pixel(x, y, 0)
            p = p + 1
示例#12
0
    def draw(self, board):
        for i in range(len(board)):
            for j in range(len(board[i])):
                if board[i][j] == 1:
                    setting = 9
                elif board[i][j] == 2:
                    setting = 4
                else:
                    setting = 0

                display.set_pixel(i, j, setting)
示例#13
0
 def update(self):
     # Clear old pixel
     # TODO we don't need to clear if no button is pressed
     display.set_pixel(self.x, self.y, 0)
     # Move left or right
     if button_a.is_pressed() and self.x > 1:
         self.x = self.x - 1
     if button_b.is_pressed() and self.x < 3:
         self.x = self.x + 1
     # Redraw
     display.set_pixel(self.x, self.y, 9)
示例#14
0
def bar_chart(value, columns=(0, 1, 2, 3, 4), *, max_value=100):
    """Draw a vertical bar chart based on percentage value
       using variable brightness levels on display."""

    ### Nine brightness levels on 5x5 LED matrix equates
    ### to 45 pixel steps - start at bottow row (no 4) and
    ### light pixels until value px_steps value is reached
    px_steps = round(value * 45 / max_value)
    for y in range(4, -1, -1):
        for x in columns:
            ### The min/max here limit values from 0 to 9
            display.set_pixel(x, y, min(MAX_BRIGHTNESS, max(0, px_steps)))
        px_steps -= MAX_BRIGHTNESS
示例#15
0
def setPixelTill(cx, cy, value=9):
    """
    Sets all pixel from (0, 0) till the given (x, y) coordinate to given value
    @param cx    : X-coordiante of the final pixel
    @param cy    : Y-coordinate of the final pixel
    @param value : Value to set for the pixels
    @returns     : Nothing
    """
    for y in range(5):
        for x in range(5):
            display.set_pixel(x, y, value)
            if x==cx and y==cy:
                return
示例#16
0
 def startGame(self):
     self.score = 0
     self.endGame = False
     display.clear()
     X = [2, 2, 2, 2, 3, 4, 4, 4, 3, 1, 0, 0, 0, 1]
     Y = [0, 1, 2, 4, 4, 3, 2, 1, 0, 0, 1, 2, 3, 4]
     for i in range(4):
         display.set_pixel(X[i], Y[i], 9)
         sleep(200)
     for i in range(4, 14):
         display.set_pixel(X[i], Y[i], 9)
         sleep(50)
     sleep(1000)
     display.clear()
示例#17
0
def update_display():
    global kills
    if DEAD:
        display.show(Image.SAD)
        return

    display.set_pixel(IDENTITY[0], IDENTITY[1], 9)

    new_kills = set()
    for x, y, val in kills:
        display.set_pixel(x, y, val)
        if val > 0:
            new_kills.add((x, y, val - 1))
    kills = new_kills
示例#18
0
 def reset(self):
     """ Set the lights to a series of dark/light values """
     for y in [0, 2, 4]:
         display.set_pixel(0, y, 4)
         display.set_pixel(4, y, 4)
     for y in [1, 3]:
         display.set_pixel(0, y, 1)
         display.set_pixel(4, y, 1)
示例#19
0
    def drawExplosion(self, brightness, radius):
        x = self.properties[0]
        y = self.properties[1]
        left_of_centre = x - radius
        right_of_centre = x + radius
        above_centre = y - radius

        if left_of_centre >= game.screenMinX:
            display.set_pixel(left_of_centre, y, brightness)
            display.set_pixel(left_of_centre, above_centre, brightness)

        display.set_pixel(x, above_centre, brightness)

        if right_of_centre <= game.screenMaxX:
            display.set_pixel(right_of_centre, y, brightness)
            display.set_pixel(right_of_centre, above_centre, brightness)
示例#20
0
def swish(direction):
    ostart = 0 if direction == RIGHT else 5
    oend = 9 if direction == RIGHT else -5
    step = 1 if direction == RIGHT else -1
    istart = 1 if direction == RIGHT else 3
    iend = 4 if direction == RIGHT else -1
    for i in range(ostart, oend, step):
        display.clear()
        if -1 < i < 5:
            display.set_pixel(i, 2, 9)
        for j in range(istart, iend, step):
            k = i - j * step
            brightness = 9 - (2 * j)
            if 5 > k >= 0:
                display.set_pixel(k, 2, brightness)
        sleep(100)
示例#21
0
def rccar_rx(cmd):
    global px_cur, py_cur
    px_cmd = int(cmd / 100)
    py_cmd = cmd % 100

    px = mymap(px_cmd, 0, 100, 0, 5)
    py = mymap(py_cmd, 0, 100, 0, 5)
    if px_cur != px or py_cur != py:
        di.set_pixel(px_cur, py_cur, 0)
    di.set_pixel(px, py, 9)

    px_cur = px
    py_cur = py

    go_value = -(py_cmd - 50) * 2
    percent = (px_cmd - 50)

    go_value = -mymap(py_cmd, 0, 99, -100, 100)
    percent = mymap(px_cmd, 0, 99, -100, 100)

    big = max(abs(go_value), abs(percent))

    if big > 100:
        big = 100
    if big <= -100:
        big = -100
    big_p = big * abs(percent) / 100

    if go_value > 0:
        if percent > 0:
            r = big
            l = big - 2 * big_p
        else:
            l = big
            r = big - 2 * big_p
    else:
        if percent > 0:
            r = -big
            l = -big + 2 * big_p
        else:
            l = -big
            r = -big + 2 * big_p

    #print("x=%i,y=%i,go=%i,lr=%i,l=%i,r=%i" %(px_cmd,py_cmd,go_value,percent,l,r))

    move_motor_lr(int(l), int(r))
示例#22
0
def leds(part,va):#pixel_debug
    if part==1: # tx
        va = va *3 % 10
        di.set_pixel(4, 4, va)
    elif part==2:#master
        di.set_pixel(3, 4, va)
    else: #3 Rx
        return
        va = va % 30
        for i in range(3):
            if va >=9:
                di.set_pixel(i, 4, 9)
            elif va<0:
                di.set_pixel(i, 4, 0)
            else:
                di.set_pixel(i, 4, va)
            va -=10
示例#23
0
def main():
    sb = ScrollBit()
    sd = ScrollDisplay(100)
    bd = BitDisplay(7)

    while True:
        sb.set_pixel(sd.x, sd.y, sd.b)
        sb.show()
        display.set_pixel(bd.x, bd.y, bd.b)

        sd.step()
        bd.step()

        sleep(200)

        sb.clear()
        display.clear()
示例#24
0
def main():
    state = READY
    while True:
        # Ready state
        if state == READY:
            while True:
                if button_a.is_pressed():
                    state = SAMPLE_DATA
                    break
                elif button_b.is_pressed():
                    radio.on()
                    radio.send("done")
                    radio.off()
                else:
                    display.show(Image.ARROW_W)
                sleep(100)
        # Sample Data state
        elif state == SAMPLE_DATA:
            data_sent = 0  # Reset data sent value
            countdown(3)  # Show countdown on the Microbit LED
            display.show(Image.TARGET)
            radio.on()
            initial_time = running_time()
            while (running_time() - initial_time) < SAMPLE_DURATION:
                t0 = running_time()
                if data_sent == 0:  # Turn off all Microbit LEDs
                    display.clear()
                cx, cy = divmod(
                    data_sent,
                    5)  # Get current LED pixel coordinate of the BBC Microbit
                radio.send(str(accelerometer.get_values()))
                display.set_pixel(4 - cx, cy, 9)
                data_sent = 0 if data_sent >= 24 else data_sent + 1  # Increase and limit data_sent value within 0-24 range
                wait_t = SAMPLE_INTERVAL - (running_time() - t0
                                            )  # Time till next sample
                if (wait_t > 0):
                    sleep(wait_t)
            radio.send("done")
            radio.off()
            state = READY
        # Exit state
        elif state == EXIT:
            display.show(Image.HAPPY)
            return 0
        sleep(100)
示例#25
0
def rccar_tx(did):
    global px_cur, py_cur
    [x, y, z] = accelerometer.get_values()
    px = mymap(x, -1000, 1000, 0, 5)
    py = mymap(y, -1000, 1000, 0, 5)
    #print("(%i,%i,%i,%i,%i)"%(x,y,z,px,py))

    if px_cur != px or py_cur != py:
        di.set_pixel(px_cur, py_cur, 0)
    di.set_pixel(px, py, 9)
    px_cur = px
    py_cur = py

    px_cmd = mymap(x, -1000, 1000, 0, 100)
    py_cmd = mymap(y, -1000, 1000, 0, 100)

    cmd = px_cmd * 100 + py_cmd
    txp(did, 23, str(cmd))
示例#26
0
def StartCountdown():
    global lookingForGame
    global gameStarted
    global ball
    global points
    
    display.clear()
    for i in range(5, -1, -1):
        display.show(i)
        time.sleep(1)
    
    display.clear()
    lookingForGame = False
    points = 0
    gameStarted = True
    prevBallMove = time.ticks_ms()
    if(not ball is None):
        display.set_pixel(ball.x, ball.y, 9)
        CheckBounce()
示例#27
0
def check_crash(car, enemy, barrier):
    """ Check for a crash between car and enemy """
    if (car.x == enemy.x) and (car.y == enemy.y):
        # Repeat crazy flashes on crash
        for _ in range(5):
            for y in range(5):
                display.set_pixel(0, y, 9)
                display.set_pixel(4, y, 9)
            sleep(100)
            for y in range(5):
                display.set_pixel(0, y, 0)
                display.set_pixel(4, y, 0)
            sleep(100)
        barrier.reset()
示例#28
0
def main():
    """ entry point to the app """

    # loop forever
    while True:
        # generate a random number to represent the number of leds to show ...
        num = random.randint(0, 10)

        # clear the display from the previous game ...
        display.clear()

        # a list to keep track of which leds have been used ...
        used = []

        # loop 'num' times ...
        for i in range(num):
            # generate a random number to represent which led to show ...
            led = random.randint(0, NUM_LEDS - 1)

            # if the led has already been used,
            # generate another random number ...
            while led in used:
                led = random.randint(0, NUM_LEDS - 1)
            used.append(led)

            # get the coords for the led to show ...
            x, y = get_coords(led)

            # show the led ...
            display.set_pixel(x, y, 9)

        # get the answer from the user ...
        input_num = get_button_presses()

        # if the answer is correct, display WIN otherwise LOSE ...
        if num == input_num:
            display.scroll("WIN!")
        else:
            display.scroll("LOSE!")
示例#29
0
def main():
    """ entry point to the app """

    # loop forever
    while True:
        # generate a random number to represent the number of leds to show ...
        num = random.randint(0, 10)

        # clear the display from the previous game ...
        display.clear()

        # a list to keep track of which leds have been used ...
        used = []

        # loop 'num' times ...
        for i in range(num):
            # generate a random number to represent which led to show ...
            led = random.randint(0, NUM_LEDS-1)

            # if the led has already been used,
            # generate another random number ...
            while led in used:
                led = random.randint(0, NUM_LEDS-1)
            used.append(led)

            # get the coords for the led to show ...
            x, y = get_coords(led)

            # show the led ...
            display.set_pixel(x, y, 9)

        # get the answer from the user ...
        input_num = get_button_presses()

        # if the answer is correct, display WIN otherwise LOSE ...
        if num == input_num:
            display.scroll("WIN!")
        else:
            display.scroll("LOSE!")
示例#30
0
    def logic(self):
        display.clear()
        p1 = pin1.read_analog()
        p2 = pin2.read_analog()
        if p1 <= 204:
            x = 0
        elif 204 < p1 <= 408:
            x = 1
        elif 408 < p1 <= 612:
            x = 2
        elif 612 < p1 <= 816:
            x = 3
        else:
            x = 4

        if p2 <= 204:
            y = 4
        elif 204 < p2 <= 408:
            y = 3
        elif 408 < p2 <= 612:
            y = 2
        elif 612 < p2 <= 816:
            y = 1
        else:
            y = 0

        display.set_pixel(*self.pix)
        display.set_pixel(x, y, 9)

        if [x, y, 9] == self.pix:
            self.pix = None
            display.show(Image.HAPPY)
            music.play(music.JUMP_UP)
            sleep(500)
        if self.btn_pressed():
            sleep(150)
            self.set_random_pix()
示例#31
0
 def calibrate():
     t = running_time()
     lastrt = t
     prev = 0
     calibrated = False
     while not calibrated:
         r = pin0.read_analog() - 11
         r = abs(r) / 900 * 5
         r = int(r) if r < 6 else 5
         if (r == 5 and prev != 5) or (r == 0 and prev != 0):
             t = running_time()
         prev = r
         if running_time() - t > 3000:
             lastrt = running_time()
             if r == 0:  # No sound for more than 3 seconds
                 # Turn right
                 display.show(Image.ARROW_E)
             else:  # Saturated for more than 3 seconds
                 # Turn left
                 display.show(Image.ARROW_W)
         else:
             for y in range(0, 5):
                 for x in range(0, 5):
                     if 4 - y < r:
                         display.set_pixel(x, y, 5)
                     else:
                         display.set_pixel(x, y, 0)
             if r > 0:
                 # If there is sound, leave the leds on for .1 seconds
                 sleep(100)
             if running_time() - lastrt > 5000:
                 display.show(Image.YES)
                 sleep(1000)
                 calibrated = True
                 display.clear()
     return calibrated
def main():
	data_received = 0
	display.show(Image.HAPPY)
	while True:
		response = radio.receive()
		if response is not None:							# Some data received
			uart.write(response+"\n")						# Write received data with line break on serial bus
			if data_received == 0:
				display.clear()								# Clear Microbit LEDs
			if "," in response:								# "(x,y,z)" data received
				cy, cx = divmod(data_received, 5)
				display.set_pixel(cx, cy, 9)
				# Increase and limit data_received value within 0-24 range
				data_received = 0 if data_received >= 24 else data_received+1
			elif response == "done":
				data_received = 0
				display.show(Image.YES)
			elif response == "exit":
				display.show(Image.HAPPY)
				sleep(2000)
				display.clear()
				break
        else:
			sleep(100)
示例#33
0
def level():
    global row, col
    bright = 4
    for x in range(1, 5):
        display.set_pixel(x, 0, 0)
    for y in range(0, 5):
        display.set_pixel(0, y, 0)
    row = accelerometer.get_x()  #pitch 2 row
    row = min(max(1,
                  int(row / 200) + 2),
              4)  # roll sensitivity row/60=narrow 400=wide + tilt factor
    display.set_pixel(row, 0, bright)
    col = accelerometer.get_y()  # roll 4 bit cols
    col = min(
        max(3,
            int(col / 200) + 2),
        4)  #pitch sensitivity 200 horizontal 300 more vertical + tilt factor
    display.set_pixel(0, col, bright)
示例#34
0
def leds(part, va):  #pixel_debug
    va = va % 10
    if part == 1:  # tx
        va = va * 3 % 10
        di.set_pixel(4, 4, va)
    elif part == 0:  # rxc
        di.set_pixel(0, 4, va)
    elif part == 2:  #master
        di.set_pixel(3, 4, va)
    else:  #3 Rx
        pass
示例#35
0
def display_minutes(minutes):
    """Show minutes"""
    i = 0
    for y_coord in range(5):
        for x_coord in range(5):
            i += 1
            if i <= minutes:
                display.set_pixel(x_coord, y_coord, 9)
            else:
                if x_coord == 0 and y_coord == 0 and minutes < 1:
                    display.set_pixel(x_coord, y_coord, 4)
                else:
                    display.set_pixel(x_coord, y_coord, 0)
示例#36
0
def show_id():
    di.clear()

    for id in uids:
        if id > 0:
            uid = id - 1
            di.set_pixel(uid % 5, int(uid / 5), 2)

    uid = lid - 1
    di.set_pixel(uid % 5, int(uid / 5), 5)

    id = mid
    if id > 0:
        uid = id - 1
        di.set_pixel(uid % 5, int(uid / 5), 9)
def play(midi, notes):
    led = 0
    duration = octave = 4
    bpm, ticks = music.get_tempo()
    mpt = 60000 / bpm / ticks

    try:
        for note in notes:
            try:
                note, duration = note.split(':')
                duration = int(duration)
            except:
                pass

            try:
                octave = int(note[-1])
                note = note[:-1]
            except (ValueError, IndexError):
                pass

            note = note.lower()
            midinote = NOTES.get(note[0])

            if midinote is not None:
                if note.endswith('#'):
                    midinote += 1
                elif len(note) > 1 and note.endswith('b'):
                    midinote -= 1

                midinote = max(0, min(127, midinote + 12 * octave))
                midi.note_on(midinote, 96)
                display.set_pixel(led, 0, 5)

            sleep(duration * mpt)

            if midinote is not None:
                midi.note_off(midinote)
                display.set_pixel(led, 0, 0)
                led = (led+1) % 5

        # make sure led and last note is turned off
        if midinote is not None:
            display.set_pixel(led, 0, 0)
            midi.note_off(midinote)
    except:
        # Send all sound off to prevent hanging notes
        midi.control_change(0x78, 0)
示例#38
0
def fade(how_much=1):
    for x in range(5):
        for y in range(5):
            brightness = display.get_pixel(x, y)
            if brightness >= how_much:
                display.set_pixel(x, y, brightness - how_much)
示例#39
0
 def draw(self):
     # Draw the droplet (with fainter tail)
     display.set_pixel(self.x[2], self.y[2], 0)
     display.set_pixel(self.x[1], self.y[1], 1)
     display.set_pixel(self.x[0], self.y[0], 9)
示例#40
0
文件: pong.py 项目: paulegan/microbit
def set_pixel(x=2, y=2):
    """Set the specified pixel to max brightness and fade everything else."""
    fade_display()
    return display.set_pixel(x, y, 9)
示例#41
0
文件: tilty.py 项目: blogmywiki/tilty
pause = 100
level = 1
accelerometer_sensitivity = 1 / 300

# set initial position
x, y = 2, 2
yaccel, xaccel = get_xy()
y = max(0, min(4, int(y + yaccel)))
x = max(0, min(4, int(x + xaccel)))

while pause > 0:
    yaccel, xaccel = get_xy()
    newy = max(0, min(4, int(y + yaccel)))
    newx = max(0, min(4, int(x + xaccel)))
    if newy != y or newx != x:
        display.set_pixel(x, y, 1)
        x, y = newx, newy
        display.set_pixel(x, y, 9)
    else:
        display.set_pixel(newx, newy, 9)
    pixels = count_lit_pixels()
    if pixels == 25:
        play(POWER_UP, wait=False)
        level += 1
        pause -= 5
        sleep(200)
        display.show(str(level))
        sleep(1000)
        display.clear()
    sleep(pause)
示例#42
0
#
# Filename = "mbSimplePong.py"

from microbit import display, Image, accelerometer, sleep, button_a, reset
from random import randint

maxScore = 6    # Change this if you want more rounds / game.
gestureSensitivity = 120
delay = 400

# Set initial position of pong game's "paddle"
padY = 4
padX = 2

# Display initial paddle
display.set_pixel(padX, padY, 9)

# Set initial position of pong game's "ball"
ballX = 0
ballY = 0

# Display initial ball, blink ball 3 times
# to attract the player's attention
for i in range(0, 3):
    display.set_pixel(ballX, ballY, 5)
    sleep(delay)
    display.set_pixel(ballX, ballY, 0)
    sleep(delay)

ballX = randint(0, 4)    # Randomly select column to serve ball in.
display.set_pixel(ballX, ballY, 5)
示例#43
0
def fade():
    for x in range(5):
        for y in range(5):
            brightness = display.get_pixel(x, y)
            if brightness > 0:
                display.set_pixel(x, y, brightness - 1)
示例#44
0
"""
LEDs start at random brightnesses and deltas (either up or down) and bounce
back when brightness goes out of its boundaries.
"""
import random

from microbit import display

[[display.set_pixel(x, y, 4) for y in range(5)] for x in range(4)]
delta = [[random.choice((-1, +1)) for _ in range(5)] for _ in range(5)]

while True:
    for x in range(5):
        for y in range(5):
            brightness = display.get_pixel(x, y)
            if ((brightness == 9 and delta[x][y] > 0)
                    or (brightness == 0 and delta[x][y] < 0)):
                delta[x][y] = -delta[x][y]
            if random.random() > .5:
                brightness += delta[x][y]
            display.set_pixel(x, y, brightness)
示例#45
0
def swap_led(x, y):
    """ Alternate an LED between light and dark """
    if display.get_pixel(x, y) == 1:
        display.set_pixel(x, y, 4)
    else:
        display.set_pixel(x, y, 1)
                led = (led+1) % 5

        # make sure led and last note is turned off
        if midinote is not None:
            display.set_pixel(led, 0, 0)
            midi.note_off(midinote)
    except:
        # Send all sound off to prevent hanging notes
        midi.control_change(0x78, 0)


# wait for button A press before initializing the UART
# to allow uploading of new firmware
while True:
    if button_a.is_pressed():
        display.set_pixel(0, 0, 0)
        break

    display.set_pixel(0, 0, 5)
    sleep(100)
    display.set_pixel(0, 0, 0)
    sleep(100)

# Initialize UART for MIDI
uart.init(baudrate=31250)
midi = MidiOut(uart)

tune = program = 0
# send a PROGRAM CHANGE to set instrument to #0 (Grand Piano)
midi.program_change(program)
# set led on first 4 rows of display to indicate current tune (1-20)
示例#47
0
 def show(self):
     # Completely untested, I had to write it blindly :(
     display.clear()
     for y, row in enumerate(self.rows):
         for x, pixel in enumerate(row):
             display.set_pixel(x, y, pixel)
示例#48
0
    (0, 1),
    (2, 0),
]

terrain_multiplier = 5
pos = 0

while True:
    sleep(100)
    if -256 < accelerometer.get_y() < 450:
        bird = max(0, bird - 1)
    elif 568 < accelerometer.get_y() < 1024:
        bird = min(4, bird + 1)

    display.clear()
    display.set_pixel(0, bird, 9)

    pos_terrain = pos // terrain_multiplier
    lost_status = False
    for column, (top, bottom) in enumerate(
            terrain[pos_terrain:pos_terrain + 5]):
        for y in range(top):
            display.set_pixel(column, y, 4)
            if column == 0 and bird == y:
                lost_status = True
        for y in range(bottom):
            display.set_pixel(column, 4 - y, 4)
            if column == 0 and bird == (4 - y):
                lost_status = True
    if lost_status:
        display.show(Image.SAD)
    return random.randrange(100)


def xy(channel):
    x = channel // 20
    y = channel // 4 % 5
    return x, y

radio.on()

channel = new_channel()
x, y = xy(channel)
radio.config(channel=channel)

while True:
    display.set_pixel(x, y, 4)
    radio.send('hello, microbit')
    display.set_pixel(x, y, 0)
    if accelerometer.is_gesture('shake'):
        channel = new_channel()
        radio.config(channel=channel)
        x, y = xy(channel)
    if button_a.was_pressed():
        channel += 1
        radio.config(channel=channel)
        if channel > 99:
            channel = 0
        x, y = xy(channel)
    if button_b.was_pressed():
        channel -= 1
        radio.config(channel=channel)
                             value >> 7 if lsb else value, ch=ch)
        if lsb and control < 20:
            self.channel_message(CONTROLLER_CHANGE, control + 32, value, ch=ch)
    def program_change(self, program, ch=None):
        self.channel_message(PROGRAM_CHANGE, program, ch=ch)


# -----------------------------------------------------------------------------
# Main script

from microbit import button_a, display, sleep


while True:
    if button_a.is_pressed():
        display.set_pixel(0, 0, 0)
        break

    display.set_pixel(0, 0, 5)
    sleep(100)
    display.set_pixel(0, 0, 0)
    sleep(100)

# Initialize UART for MIDI
midi = MidiOut()

while True:
    # send NOTE ON for middle C (60) at velocity 100
    midi.note_on(60, 100)
    display.set_pixel(0, 0, 5)
    sleep(500)
示例#51
0
"""
LEDs start at random brightnesses and go up or down randomly by one level.
"""
import random

from microbit import display

while True:
    for x in range(5):
        for y in range(5):
            brightness = display.get_pixel(x, y)
            brightness += random.randrange(-1, 2)
            if brightness > 9:
                brightness = 9
            elif brightness < 0:
                brightness = 0
            display.set_pixel(x, y, brightness)
示例#52
0
"""
Because cool computers have lots of blinking lights (or used to be).

Each LED gets a random brightness.
"""
import random

from microbit import display, sleep

while True:
    for x in range(5):
        for y in range(5):
            display.set_pixel(x, y, random.randrange(0, 10))
    sleep(10)
示例#53
0
from microbit import button_a, button_b, display, sleep

delay = 20


def fade():
    for x in range(5):
        for y in range(5):
            brightness = display.get_pixel(x, y)
            if brightness > 0:
                display.set_pixel(x, y, brightness - 1)

while True:
    for x in range(5):
        for y in range(5):
            fade()
            if button_a.is_pressed():
                delay += 1
            elif delay > 0 and button_b.is_pressed():
                delay -= 1
            display.set_pixel(x, y, 9)
            for _ in range(delay):
                sleep(1)