#include <iostream>
#include <windows.h>
#include <conio.h>
using namespace std;

struct Lamp {
  unsigned int X, Y;
  unsigned short color;
};

const unsigned int l_antal = 42;

int random(int lowest_number, int highest_number)
{
  int range = highest_number - lowest_number + 1;
  return lowest_number + int(range * rand()/(RAND_MAX + 1.0));
}

void setcolor(unsigned short color)
{
  HANDLE hcon = GetStdHandle(STD_OUTPUT_HANDLE);
  SetConsoleTextAttribute(hcon,(WORD)(color));
}

void gotopos(int xpos, int ypos)
{
  COORD scrn;    
  HANDLE hOuput = GetStdHandle(STD_OUTPUT_HANDLE);
  scrn.X = xpos - 1; scrn.Y = ypos - 1;
  SetConsoleCursorPosition(hOuput,scrn);
}

void initlamps(Lamp lamps[])
{
  unsigned int i = 0, px, py, xc;
  for (py = 1; py <= 11; py++) {
    if (py <= 3) {
      xc = (py-1);
    } else if (py <= 7) {
      xc = (py-3);
    } else {
      xc = (py-5);
    }
    for (px = py - xc; px <= py + xc; px += 2) {   
      lamps[i].color = 0;
      lamps[i].X = px + (8-py);
      lamps[i].Y = py + 6;
      i++;
    }  
  }
}
  
void blinklamps(Lamp lamps[])
{
  unsigned short color;
  for (int i = 0; i < l_antal; i++) {
    do {
      color = random(9,15);
    } while (color == lamps[i].color);
    lamps[i].color = color;
    setcolor(lamps[i].color);
    gotopos(lamps[i].X,lamps[i].Y);
    cout << "\xF9";
  }  
  gotopos(43,25);
}  

int main(void)
{
  Lamp lamps[l_antal];
  srand(time(0));
  system("CLS");
  setcolor(14);
  cout << "Ett litet julkort\n";
  setcolor(15);
  cout << "=================\n\n";
  setcolor(7);
  cout << "       *\n"
       << "      *";
  setcolor(12);
  cout << "*";
  setcolor(7);
  cout << "*\n"
       << "       *\n";
  setcolor(2);
  cout << "      * *\n"
       << "     * * *\n"
       << "    * * * *\n"
       << "     * * *\n"
       << "    * * * *\n"
       << "   * * * * *\n"
       << "  * * * * * *\n"
       << "   * * * * *\n"
       << "  * * * * * *\n"
       << " * * * * * * *\n"
       << "* * * * * * * *\n";
  setcolor(6);
  cout << "      ***\n      ***\n";
  setcolor(12);
  cout << "     *****\n\n";
  setcolor(15);
  cout << "God Jul 2004 och Gott Nytt \x8Fr 2005\n\t\x94nskar Jocke \"Firetech\" Andersson\n\n";
  setcolor(14);
  cout << "Tryck p\x86 valfri tangent f\x94r att avsluta...";
  initlamps(lamps);
  bool blink = true;
  int i;
  while (blink) {
    blinklamps(lamps);
    for (i = 1; i <= 20 && blink; i++) { 
      if (kbhit()) {
        blink = false;
      }
      Sleep(50);
    }
  }
  setcolor(7);
  return 0;
}

