Program: Digital Snowstorm





Here's some multi-coloured screen-candy for you to try.







Select and copy the C++ source-code at the bottom of this post.


Paste into a text editor, such as Nano or Geany.


Then save the new file, ending in .cpp


I used snowstorm.cpp


To compile from the command-line:


    g++ -o snowstorm.cpp snow


To run from the command-line:


    ./snow


To speed the program up, reduce the value that the usleep() function uses - try 100


To slow it down, increase the value.













Code is below...




#include <cstdlib>  // To use random number function
#include <iostream>  // To use the screen - "channel out" cout, flush
#include <unistd.h>  // To slow things down using usleep function
#include <sstream>  // To convert between numbers and strings


using namespace std;  // Want to use short abbreviations


int main()
{
 // Will count number of flakes
 // This is used to determine which colour to display
 int snowflake = 0;


 // Do this code again and again forever...
 while ( true )
 {
  // Pick a random column number for the screen
  int column = random() % 80;

  // Pick a random row number
  int row = random() % 25;


  // Convert the column number to a string of characters
  stringstream columnConverter;
  columnConverter << column;
  string columnString;
  columnConverter >> columnString;


  // Convert the row number to a string of characters
  stringstream rowConverter;
  rowConverter << row;
  string rowString;
  rowConverter >> rowString;


  // Position the cursor on screen at particular row and column

  cout << "\e[" + rowString + ";" + columnString + "H";

  // Decide what colour to use to display snowflake
  switch ( snowflake % 3 )
  {
   case 0: cout << "\e[38;5;226m"; break; // Yellow
   case 1: cout << "\e[31m"; break; // Red
   case 2: cout << "\e[0m"; break; // White/terminal default colour
  }
 



  // Increase snowflake counter
  snowflake++;


  // Display 1 or 0
  // (obtained by MOD 2 remainder on the number of snowflakes)
  cout << snowflake % 2;


  // Update screen NOW!
  cout << flush;



  // Pause for part of a second
  usleep(10000);
 }



 return 0;
}