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

// Exercise B3d 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 gates_8_input.sv.
//
// Keys: key [0] a, key [1] b, key [2] c, key [3] d. The LEDs: led [0] y_and,
// led [1] y_nand, led [2] y_or, led [3] y_nor. The screen shows 8 lamps in a
// row: A, B, C, D, AND, NAND, OR, NOR; inputs in blue, outputs in green.
//
// Inputs E-H of each chip are fixed as on the breadboard: 1 for the 4068, 0
// for the 4078.
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
);

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

    wire a = key [0];
    wire b = key [1];
    wire c = key [2];
    wire d = key [3];

    logic y_and;
    logic y_nand;
    logic y_or;
    logic y_nor;

    gates_8_input i_gates_8_input
    (
        .a        ( a       ),
        .b        ( b       ),
        .c        ( c       ),
        .d        ( d       ),
        .rest_and ( 4'b1111 ),
        .rest_or  ( 4'b0000 ),
        .y_and    ( y_and   ),
        .y_nand   ( y_nand  ),
        .y_or     ( y_or    ),
        .y_nor    ( y_nor   )
    );

    assign led      = { 4'b0, y_nor, y_or, y_nand, y_and };

    assign abcdefgh = '0;
    assign digit    = '0;

    //------------------------------------------------------------------------
    // 8 square lamps on the 480 x 272 screen, 40 pixels wide, 57 apart:
    // the inputs in blue, the outputs in green.  Bright when 1, dim when 0.

    wire [7:0] lamp = { y_nor, y_or, y_nand, y_and, d, c, b, a };

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

        for (int i = 0; i < 8; i ++)
            if (x >= 9' (20 + i * 57) & x < 9' (60 + i * 57) & y >= 116 & y < 156)
            begin
                if (i < 4)
                    blue  = lamp [i] ? 31 : 6;
                else
                    green = lamp [i] ? 63 : 12;
            end
    end

endmodule
