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

// Exercise BB6 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 priority_encoder.sv.
//
// Keys 7-0 are D7-D0.  The rightmost digit shows the number of the highest
// key pressed, the LEDs show Q, GS and EO, and the screen eight lamps for
// the keys, D0 on the left, with the winning one in green.

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 [2:0] q;
    logic       gs, eo;
    logic [6:0] abcdefg;

    priority_encoder i_priority_encoder
    (
        .d       ( key     ),
        .q       ( q       ),
        .gs      ( gs      ),
        .eo      ( eo      ),
        .abcdefg ( abcdefg )
    );

    assign led      = { 3'b0, eo, gs, q };
    assign abcdefgh = { abcdefg, 1'b0 };
    assign digit    = 8'b0000_0001;

    //------------------------------------------------------------------------
    // Eight square lamps, D0 on the left: blue for a pressed key, green for
    // the one that wins, dim for the others.

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

        for (int i = 0; i < 8; i ++)
            if (x >= 9' (40 + i * 52) & x < 9' (80 + i * 52) & y >= 116 & y < 156)
            begin
                if (gs & q == 3' (i))
                    green = 63;
                else if (key [i])
                    blue  = 31;
                else
                    blue  = 6;
            end
    end

endmodule
