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

// Exercise M4 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 adder8.sv.
//
// Keys 7-0 are A.  B is fixed in the code, as the wires to the rails on the
// breadboard.  The LEDs show the sum, the dot of the rightmost digit the
// carry.  The screen shows three rows of eight lamps, bit 7 on the left:
// A in blue, B in orange and the sum in green, with the carry left of it.

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
);

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

    localparam [7:0] B = 8'd45;  // 0010 1101, as the wires on the breadboard

    logic [7:0] sum;
    logic       carry;

    adder8 i_adder8
    (
        .a     ( key   ),
        .b     ( B     ),
        .sum   ( sum   ),
        .carry ( carry )
    );

    assign led      = sum;
    assign abcdefgh = { 7'b0, carry };
    assign digit    = 8'b0000_0001;

    //------------------------------------------------------------------------
    // Lamps 30 pixels wide, 44 apart, from x = 90: rows at y = 60 (A),
    // 120 (B) and 180 (the sum); the carry at x = 46 in the row of the sum

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

        for (int i = 0; i < 8; i ++)
            if (x >= 9' (90 + i * 44) & x < 9' (120 + i * 44))
            begin
                if (y >= 60 & y < 90)
                begin
                    green = key [7 - i] ? 40 : 8;
                    blue  = key [7 - i] ? 31 : 6;
                end

                if (y >= 120 & y < 150)
                begin
                    red   = B [7 - i] ? 31 : 6;
                    green = B [7 - i] ? 32 : 6;
                end

                if (y >= 180 & y < 210)
                    green = sum [7 - i] ? 63 : 12;
            end

        if (x >= 46 & x < 76 & y >= 180 & y < 210)
            green = carry ? 63 : 12;
    end

endmodule
