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

// Exercise P7 in the hackathon setup of Basics-Graphics-Music (BGM):
// https://github.com/yuri-panchul/basics-graphics-music
//
// Copy a directory such as hackathon/problems/3_d_flip_flop, replace its
// hackathon_top.sv with this file and add serial_compare.sv.
//
// The comparator runs from slow_clock; reset starts a new comparison.
// Key 1 is the bit of A and key 0 the bit of B: hold them through a tick of
// slow_clock, lowest bits first.  The LEDs and the rightmost digit are as in
// lab_top, and the screen shows a traffic light of three square lamps.

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 gt, lt, eq;

    serial_compare i_serial_compare
    (
        .clk ( slow_clock ),
        .rst ( reset      ),
        .a   ( key [1]    ),
        .b   ( key [0]    ),
        .gt  ( gt         ),
        .lt  ( lt         ),
        .eq  ( eq         )
    );

    assign led      = { 5'b0, lt, eq, gt };

    //                 a   b     c     d   e     f     g   h
    assign abcdefgh = { lt, 1'b0, 1'b0, gt, 1'b0, 1'b0, eq, 1'b0 };
    assign digit    = 8'b0000_0001;

    //------------------------------------------------------------------------
    // A traffic light on the screen: three square lamps in a dark box, red
    // on top, bright when on and dim when off

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

        if (x >= 210 & x < 270 & y >= 40 & y < 232)
        begin
            red   = 2;
            green = 4;
            blue  = 2;
        end

        if (x >= 220 & x < 260)
        begin
            if (y >= 50 & y < 90)
                red = lt ? 31 : 8;
            else if (y >= 116 & y < 156)
            begin
                red   = eq ? 31 : 8;
                green = eq ? 50 : 12;
            end
            else if (y >= 182 & y < 222)
                green = gt ? 63 : 14;
        end
    end

endmodule
