// Board configuration: tang_nano_9k_lcd_480_272_tm1638_hackathon
// This module uses few parameterization and relaxed typing rules

// Exercise BB5 in the hackathon setup of Basics-Graphics-Music (BGM):
// https://github.com/yuri-panchul/basics-graphics-music
//
// Copy a directory such as hackathon/problems/1_gates_and_muxes, replace its
// hackathon_top.sv with this file and add decoder.sv.
//
// Keys 3-0 are the code D C B A.  The LEDs show Q7-Q0, the rightmost digit
// the number of the output that is 1, and the screen ten lamps, Q0 on the
// left: like the two LED modules on the breadboard.

module hackathon_top
(
    input  logic       clock,
    input  logic       slow_clock,
    input  logic       reset,

    input  logic [7:0] key,
    output logic [7:0] led,

    // A dynamic seven-segment display

    output logic [7:0] abcdefgh,
    output logic [7:0] digit,

    // LCD screen interface

    input  logic [8:0] x,
    input  logic [8:0] y,

    output logic [4:0] red,
    output logic [5:0] green,
    output logic [4:0] blue,

    inout  logic [3:0] gpio
);

    //------------------------------------------------------------------------

    logic [9:0] q;

    decoder i_decoder
    (
        .code ( key [3:0] ),
        .q    ( q         )
    );

    assign led = q [7:0];

    //------------------------------------------------------------------------
    // The digit whose output is 1, on a 7-segment display: a is the top
    // segment, g the middle one.  No output at 1 (codes 10-15): blank.

    logic [6:0] abcdefg;

    always_comb
        case (q)
        10'b00_0000_0001: abcdefg = 7'b111_1110;  // 0
        10'b00_0000_0010: abcdefg = 7'b011_0000;  // 1
        10'b00_0000_0100: abcdefg = 7'b110_1101;  // 2
        10'b00_0000_1000: abcdefg = 7'b111_1001;  // 3
        10'b00_0001_0000: abcdefg = 7'b011_0011;  // 4
        10'b00_0010_0000: abcdefg = 7'b101_1011;  // 5
        10'b00_0100_0000: abcdefg = 7'b101_1111;  // 6
        10'b00_1000_0000: abcdefg = 7'b111_0000;  // 7
        10'b01_0000_0000: abcdefg = 7'b111_1111;  // 8
        10'b10_0000_0000: abcdefg = 7'b111_1011;  // 9
        default:          abcdefg = 7'b000_0000;
        endcase

    assign abcdefgh = { abcdefg, 1'b0 };
    assign digit    = 8'b0000_0001;

    //------------------------------------------------------------------------
    // Ten square lamps on the 480 x 272 screen, 30 pixels wide, 44 apart,
    // Q0 on the left.  Bright green when 1, dim when 0.

    always_comb
    begin
        red   = 0;
        green = 0;
        blue  = 0;

        for (int i = 0; i < 10; i ++)
            if (x >= 9' (27 + i * 44) & x < 9' (57 + i * 44) & y >= 121 & y < 151)
                green = q [i] ? 63 : 12;
    end

endmodule
