# Zap the Rat - Python3 Game for BBC micro:bit
# Tony Goodhew - 4 June 2018
from microbit import*
def grid(n):  # Developed separately and dropped in
    display.clear()
    for y in range(5):
        for x in range(5):
            if n > 0:
                display.set_pixel(x, y,7)
                n = n - 1

#Circuit LED co-ordinates - round the edge
LEDx =(0,0,0,0,0,1,2,3,4,4,4,4,4,3,2,1)
LEDy =(0,1,2,3,4,4,4,4,4,3,2,1,0,0,0,0)
SSx =(1,2,3,1,3,1,2,3)
SSy =(1,1,1,2,2,3,3,3)
def ssq():
    for i in range(8):
        display.set_pixel(SSx[i],SSy[i],9)
    sleep(100)
    display.clear()
def lsq():
    for i in range(16):
        display.set_pixel(LEDx[i],LEDy[i],9)
    sleep(100)
    display.clear()
def centre():
    display.set_pixel(2,2,9)
    sleep(100)
    display.clear()
def zero():
    for j in range(4):
        centre()
        ssq()
        lsq()
        ssq()
    display.scroll("0")
    display.clear()

while True:
    display.scroll('Zap the Rat')
    sleep(10)
    score = 0            # Rats zapped!
    opps = 0             # Zap opportunities
    p = 0                # Position of rat on circuit (0-15)
    delay = 150          # Initial delay between rat moves
    old_sw = 0                    # Last value of switch B
    running = True                # Loop control variable
    display.clear()
    display.set_pixel(3,2,9)           # Show Zap position

    while running:
        display.set_pixel(LEDx[p],LEDy[p],5)   # Show rat
        if p == 10: opps = opps +1        # Incr opps - in (4,2)
        sleep(delay - score * 20) # Wait - gets faster
        sw = button_b.is_pressed()            # Read switch B
        pixel = display.get_pixel(4,2)         # Rat in Zap position?
        display.set_pixel(LEDx[p],LEDy[p],0)   # Hide rat
        if old_sw == 0 and sw == True and pixel == 5: # Hit?
            score = score +1              # Increment hits
            display.set_pixel(1,score,9)  # Show hits
            if score == 3:                # Game over ?
                running = False           # Stop looping
            p = -1            # Position of next rat
        old_sw = sw            # Store switch value
        p = p + 1              # Update rat position
        if p > 15:             # Rat pointer out of range?
            p = 0              # reset to start position

    display.clear()  # Game over - display opportunities
    opps = opps - 3  # Remove successful opportunities
    display.scroll('SCORE')
    if opps > 25:  # Reduce missed opps to 25 max
        opps = 25
    if opps == 0:
        zero()
    else:
        grid(opps)
    sleep(5000)
    display.clear()  # Tidy display