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

// Exercise M12 in the hackathon setup of Basics-Graphics-Music (BGM):
// https://github.com/yuri-panchul/basics-graphics-music
//
// Copy a directory such as hackathon/problems/4_binary_counter, replace its
// hackathon_top.sv with this file and add counter_race.sv.
//
// The counters run from slow_clock.  The LEDs show the binary count (3-0)
// and the Johnson code (7-4), the rightmost digit the traffic light as in
// lab_top, and the screen 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 [3:0] binary, johnson;
    logic       a_gt_b, a_eq_b, a_lt_b;

    counter_race i_counter_race
    (
        .clk     ( slow_clock ),
        .rst     ( reset      ),
        .binary  ( binary     ),
        .johnson ( johnson    ),
        .a_gt_b  ( a_gt_b     ),
        .a_eq_b  ( a_eq_b     ),
        .a_lt_b  ( a_lt_b     )
    );

    assign led      = { johnson, binary };

    //                 a       b     c     d       e     f     g       h
    assign abcdefgh = { a_lt_b, 1'b0, 1'b0, a_gt_b, 1'b0, 1'b0, a_eq_b, 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 = a_lt_b ? 31 : 8;
            else if (y >= 116 & y < 156)
            begin
                red   = a_eq_b ? 31 : 8;
                green = a_eq_b ? 50 : 12;
            end
            else if (y >= 182 & y < 222)
                green = a_gt_b ? 63 : 14;
        end
    end

endmodule
