To extend your Matrix Rain effect to support multiple directions (up, down, left, right) controlled by the W, A, S, D keys, you'll need to modify your existing classes and logic to handle different orientations. Below is the complete updated code with the added feature, along with explanations for the changes.
Overview of Changes
- Direction Enumeration: Introduced an
enum called Direction to represent the four possible directions.
- Direction Handling: Added logic to handle direction changes based on user input (
W, A, S, D keys).
- MatrixColumn Adjustments: Modified the
MatrixColumn class to update positions based on the current direction.
- Rendering Adjustments: Updated the rendering logic to correctly display characters moving in different directions.
- UI Class: Provided a sample
UI class to handle color and screen operations, which was referenced in your original code.
Complete Updated Code
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
namespace Tumble
{
enum Direction
{
Down,
Up,
Left,
Right
}
class MatrixRain
{
static int consoleWidth = Console.WindowWidth;
static int consoleHeight = Console.WindowHeight;
static List<MatrixColumn> matrixColumns = new List<MatrixColumn>();
static StringBuilder bufferBuilder = new StringBuilder();
static int delayMs = 50;
static double greenHue = 120;
static double baseHue = greenHue; // Start with green (120 degrees in HSV)
static Direction currentDirection = Direction.Down;
public static void Start()
{
var tempVisible = Console.CursorVisible;
Console.CursorVisible = false;
InitializeMatrixColumns();
// Initial Update to populate the screen
for (int i = 0; i < Console.WindowHeight; i++)
{
UpdateMatrixColumns();
}
while (true)
{
try
{
SizeCheck();
UpdateMatrixColumns();
RenderMatrixRain();
Thread.Sleep(delayMs);
if (Console.KeyAvailable)
{
var ki = Console.ReadKey(true);
switch (ki.Key)
{
case ConsoleKey.Escape:
Console.CursorVisible = tempVisible;
UI.Wipe();
return;
case ConsoleKey.Spacebar:
continue;
case ConsoleKey.Subtract:
if (delayMs > 10) delayMs -= 10;
break;
case ConsoleKey.Add:
delayMs += 10;
break;
case ConsoleKey.W:
currentDirection = Direction.Up;
ResetMatrix();
break;
case ConsoleKey.S:
currentDirection = Direction.Down;
ResetMatrix();
break;
case ConsoleKey.A:
currentDirection = Direction.Left;
ResetMatrix();
break;
case ConsoleKey.D:
currentDirection = Direction.Right;
ResetMatrix();
break;
case ConsoleKey.LeftArrow:
baseHue = (baseHue - 10 + 360) % 360;
break;
case ConsoleKey.RightArrow:
baseHue = (baseHue + 10) % 360;
break;
// Quick color switch
case ConsoleKey.R:
// Red
baseHue = (greenHue + 240) % 360;
break;
case ConsoleKey.G:
// Green
baseHue = (greenHue + 0) % 360;
break;
case ConsoleKey.B:
// Blue
baseHue = (greenHue + 120) % 360;
break;
case ConsoleKey.O:
// Orange
baseHue = (greenHue + 270) % 360;
break;
case ConsoleKey.C:
// Cyan
baseHue = (greenHue + 50) % 360;
break;
case ConsoleKey.P:
// Purple
baseHue = (greenHue + 160) % 360;
break;
case ConsoleKey.M:
// Magenta
baseHue = (greenHue + 200) % 360;
break;
case ConsoleKey.Y:
// Yellow
baseHue = (greenHue + 300) % 360;
break;
}
}
}
catch (Exception)
{
// Handle or log exception
}
}
}
static void SizeCheck()
{
if (consoleWidth != Console.WindowWidth || consoleHeight != Console.WindowHeight)
{
consoleWidth = Console.WindowWidth;
consoleHeight = Console.WindowHeight;
matrixColumns.Clear();
InitializeMatrixColumns();
UI.Wipe();
for (int i = 0; i < Console.WindowHeight; i++)
{
UpdateMatrixColumns();
}
}
}
static void ResetMatrix()
{
delayMs = 50;
baseHue = 120;
consoleWidth = Console.WindowWidth;
consoleHeight = Console.WindowHeight;
matrixColumns.Clear();
InitializeMatrixColumns();
UI.Wipe();
}
static void InitializeMatrixColumns()
{
switch (currentDirection)
{
case Direction.Down:
case Direction.Up:
{
int columnCount = consoleWidth / 2; // Each character takes 2 console columns
for (int i = 0; i < columnCount; i++)
{
int x = i * 2;
int y = currentDirection == Direction.Down ? -Random.Shared.Next(1, consoleHeight) : consoleHeight + Random.Shared.Next(1, consoleHeight);
matrixColumns.Add(new MatrixColumn(x, y, Random.Shared.Next(5, 20), currentDirection));
}
break;
}
case Direction.Left:
case Direction.Right:
{
int rowCount = consoleHeight;
for (int i = 0; i < rowCount; i++)
{
int x = currentDirection == Direction.Right ? -Random.Shared.Next(1, consoleWidth) : consoleWidth + Random.Shared.Next(1, consoleWidth);
int y = i;
matrixColumns.Add(new MatrixColumn(x, y, Random.Shared.Next(5, 20), currentDirection));
}
break;
}
}
}
static void UpdateMatrixColumns()
{
foreach (var column in matrixColumns)
{
column.Update();
bool outOfBounds = false;
switch (currentDirection)
{
case Direction.Down:
outOfBounds = column.Y - column.Length > consoleHeight;
break;
case Direction.Up:
outOfBounds = column.Y < -column.Length;
break;
case Direction.Left:
outOfBounds = column.X < -column.Length;
break;
case Direction.Right:
outOfBounds = column.X - column.Length > consoleWidth;
break;
}
if (outOfBounds)
{
switch (currentDirection)
{
case Direction.Down:
column.Reset(currentDirection, -Random.Shared.Next(1, consoleHeight));
break;
case Direction.Up:
column.Reset(currentDirection, consoleHeight + Random.Shared.Next(1, consoleHeight));
break;
case Direction.Left:
column.Reset(currentDirection, consoleWidth + Random.Shared.Next(1, consoleWidth));
break;
case Direction.Right:
column.Reset(currentDirection, -Random.Shared.Next(1, consoleWidth));
break;
}
}
}
}
static void RenderMatrixRain()
{
bufferBuilder.Clear();
bufferBuilder.Append("\x1b[H"); // Move cursor to home position
int lastColor = -1;
// Depending on direction, iterate differently
switch (currentDirection)
{
case Direction.Down:
case Direction.Up:
{
for (int y = 0; y < consoleHeight; y++)
{
for (int x = 0; x < consoleWidth / 2; x++)
{
int actualX = x * 2;
var column = matrixColumns.Find(c => c.X == actualX &&
((currentDirection == Direction.Down && c.Y >= y && c.Y - c.Length < y) ||
(currentDirection == Direction.Up && c.Y <= y && c.Y + c.Length > y)));
if (column != null)
{
int depth = currentDirection == Direction.Down ? column.Y - y : y - column.Y;
char character = column.GetCharAt(depth);
int color = (depth == 0) ? 0xFFFFFF : GetColor(depth, column.Length);
if (color != lastColor)
{
bufferBuilder.Append(UI.GetColorCode(color));
lastColor = color;
}
bufferBuilder.Append(character);
}
else
{
if (lastColor != 0)
{
bufferBuilder.Append("\x1b[0m"); // Reset color
lastColor = 0;
}
bufferBuilder.Append(" "); // Full-width space
}
}
bufferBuilder.AppendLine();
}
break;
}
case Direction.Left:
case Direction.Right:
{
for (int y = 0; y < consoleHeight; y++)
{
for (int x = 0; x < consoleWidth / 2; x++)
{
int actualX = x * 2;
var column = matrixColumns.Find(c => c.Y == y &&
((currentDirection == Direction.Right && c.X - c.Length < actualX && c.X >= actualX) ||
(currentDirection == Direction.Left && c.X + c.Length > actualX && c.X <= actualX)));
if (column != null)
{
int depth = currentDirection == Direction.Right ? actualX - (column.X - column.Length) : column.X - actualX;
char character = column.GetCharAt(depth);
int color = (depth == 0) ? 0xFFFFFF : GetColor(depth, column.Length);
if (color != lastColor)
{
bufferBuilder.Append(UI.GetColorCode(color));
lastColor = color;
}
bufferBuilder.Append(character);
}
else
{
if (lastColor != 0)
{
bufferBuilder.Append("\x1b[0m"); // Reset color
lastColor = 0;
}
bufferBuilder.Append(" "); // Full-width space
}
}
bufferBuilder.AppendLine();
}
break;
}
}
Console.Write(bufferBuilder);
}
static int GetColor(int depth, int columnLength)
{
if (depth == 0) return 0xFFFFFF; // White for the leading character
double saturation = 1.0;
double minBrightness = 0.1; // Minimum brightness for the last character
double brightnessRange = 1.0 - minBrightness;
double relativeBrightness = 1.0 - (double)depth / columnLength;
double value = minBrightness + (relativeBrightness * brightnessRange);
return UI.HSVToRGB(baseHue, saturation, value);
}
}
class MatrixColumn
{
public int X { get; private set; }
public int Y { get; private set; }
public int Length { get; private set; }
private int speed;
private char[] characters;
private Direction direction;
private static readonly char[] matrixCharacters = "アイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワヲン0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray();
public MatrixColumn(int x, int y, int length, Direction dir)
{
X = x;
Y = y;
Length = length;
direction = dir;
speed = Random.Shared.Next(1, 3);
characters = new char[length];
RegenerateCharacters();
}
public void Update()
{
for (int i = 0; i < speed; i++)
{
switch (direction)
{
case Direction.Down:
Y++;
break;
case Direction.Up:
Y--;
break;
case Direction.Left:
X--;
break;
case Direction.Right:
X++;
break;
}
// Shift the existing characters
Array.Copy(characters, 0, characters, 1, Length - 1);
// Generate a new character for the leading position
characters[0] = matrixCharacters[Random.Shared.Next(matrixCharacters.Length)];
}
}
public void Reset(Direction dir, int newPosition)
{
direction = dir;
switch (direction)
{
case Direction.Down:
case Direction.Up:
Y = newPosition;
break;
case Direction.Left:
case Direction.Right:
X = newPosition;
break;
}
Length = Random.Shared.Next(5, 20);
speed = Random.Shared.Next(1, 3);
characters = new char[Length];
RegenerateCharacters();
}
private void RegenerateCharacters()
{
for (int i = 0; i < Length; i++)
{
characters[i] = matrixCharacters[Random.Shared.Next(matrixCharacters.Length)];
}
}
public char GetCharAt(int depth)
{
if (depth >= 0 && depth < Length)
{
return characters[depth];
}
return ' ';
}
}
static class UI
{
// Converts HSV to RGB and returns the color as 0xRRGGBB integer
public static int HSVToRGB(double hue, double saturation, double value)
{
double c = value * saturation;
double x = c * (1 - Math.Abs((hue / 60) % 2 - 1));
double m = value - c;
double rPrime, gPrime, bPrime;
if (hue >= 0 && hue < 60)
{
rPrime = c;
gPrime = x;
bPrime = 0;
}
else if (hue >= 60 && hue < 120)
{
rPrime = x;
gPrime = c;
bPrime = 0;
}
else if (hue >= 120 && hue < 180)
{
rPrime = 0;
gPrime = c;
bPrime = x;
}
else if (hue >= 180 && hue < 240)
{
rPrime = 0;
gPrime = x;
bPrime = c;
}
else if (hue >= 240 && hue < 300)
{
rPrime = x;
gPrime = 0;
bPrime = c;
}
else // hue >= 300 && hue < 360
{
rPrime = c;
gPrime = 0;
bPrime = x;
}
int r = (int)((rPrime + m) * 255);
int g = (int)((gPrime + m) * 255);
int b = (int)((bPrime + m) * 255);
return (r << 16) | (g << 8) | b;
}
// Returns ANSI escape code for the given 0xRRGGBB color
public static string GetColorCode(int rgb)
{
int r = (rgb >> 16) & 0xFF;
int g = (rgb >> 8) & 0xFF;
int b = rgb & 0xFF;
return $"\x1b[38;2;{r};{g};{b}m";
}
// Clears the console
public static void Wipe()
{
Console.ResetColor();
Console.Clear();
}
}
class Program
{
static void Main(string[] args)
{
// Ensure the console uses UTF-8 encoding to display characters correctly
Console.OutputEncoding = Encoding.UTF8;
// Hide the cursor
Console.CursorVisible = false;
// Start the Matrix Rain
MatrixRain.Start();
}
}
}
Explanation of the Changes
-
Direction Enumeration (Direction):
enum Direction
{
Down,
Up,
Left,
Right
}
This enum represents the four possible directions in which the matrix rain can flow.
-
Current Direction Variable:
static Direction currentDirection = Direction.Down;
Initializes the default direction to downward.
-
Handling Direction Changes:
In the Start method, added cases for W, A, S, D keys to change the direction and reset the matrix:
case ConsoleKey.W:
currentDirection = Direction.Up;
ResetMatrix();
break;
case ConsoleKey.S:
currentDirection = Direction.Down;
ResetMatrix();
break;
case ConsoleKey.A:
currentDirection = Direction.Left;
ResetMatrix();
break;
case ConsoleKey.D:
currentDirection = Direction.Right;
ResetMatrix();
break;
When the direction changes, ResetMatrix() is called to reinitialize the columns according to the new direction.
-
Initializing Matrix Columns Based on Direction:
static void InitializeMatrixColumns()
{
switch (currentDirection)
{
case Direction.Down:
case Direction.Up:
{
int columnCount = consoleWidth / 2; // Each character takes 2 console columns
for (int i = 0; i < columnCount; i++)
{
int x = i * 2;
int y = currentDirection == Direction.Down ? -Random.Shared.Next(1, consoleHeight) : consoleHeight + Random.Shared.Next(1, consoleHeight);
matrixColumns.Add(new MatrixColumn(x, y, Random.Shared.Next(5, 20), currentDirection));
}
break;
}
case Direction.Left:
case Direction.Right:
{
int rowCount = consoleHeight;
for (int i = 0; i < rowCount; i++)
{
int x = currentDirection == Direction.Right ? -Random.Shared.Next(1, consoleWidth) : consoleWidth + Random.Shared.Next(1, consoleWidth);
int y = i;
matrixColumns.Add(new MatrixColumn(x, y, Random.Shared.Next(5, 20), currentDirection));
}
break;
}
}
}
- Down/Up: Initialize columns similarly to the original code but set the
y starting positions based on direction.
- : Initialize rows by setting starting positions based on direction.
How to Use the New Features
- Change Direction:
- Press
W to make the characters fall up.
- Press
S to make the characters fall down.
- Press
A to make the characters fall left.
- Press
D to make the characters fall right.
- Adjust Speed:
- Press
+ to increase the speed of the rain.
- Press
- to decrease the speed of the rain.
- Change Color:
- Press
R, G, B, O, C, P, M, Y to quickly switch between predefined colors.
- Use the left and right arrow keys to adjust the hue incrementally.
- Exit:
- Press
Escape to exit the application.
Notes
- Character Encoding: Ensure your console supports UTF-8 encoding to properly display the characters. The
Main method sets the console encoding to UTF-8.
- Performance: Rendering complex characters and using ANSI escape codes can be performance-intensive. If you experience lag, consider optimizing the rendering logic or reducing the number of characters.
- Console Size: The application automatically detects changes in the console window size and reinitializes the rain effect accordingly.
Running the Application
- Compile the code using your preferred C# compiler or IDE.
- Run the compiled application in a console that supports ANSI escape codes (e.g., Windows Terminal, PowerShell, or any modern terminal emulator).
- Interact with the application using the keys mentioned above to change directions, colors, and speed.
Enjoy your enhanced, multi-directional Matrix Rain effect!