Razen Examples

Learn Razen through practical examples and code snippets.

Random Library (random)

# Random Library (random) # Difficulty: 1 # Description: Examples of using the Random Library in Razen ## Introduction The Random Library (`random`) provides functions for generating random numbers and making random selections in Razen. This library helps you add randomness to your programs for games, simulations, and other applications that require unpredictable values. ## Library Overview ### Random Library Functions - `int` → Generates a random integer between min and max (inclusive) - `float` → Generates a random float between min and max (inclusive) - `choice` → Chooses a random element from an array - `shuffle` → Shuffles an array ## How to Use the Random Library ### Library Import To use the Random Library in Razen, you first need to import it using the `lib` keyword: ```razen lib random; ``` ### Function Calling Once imported, you can call functions from the library using the double colon `::` syntax: ```razen random::functionName(parameters); ``` **Note about bracket notation (Legacy):** In older versions of Razen (before beta v0.1.75), you could also use bracket notation for library functions: ```razen # DEPRECATED - Only works in Razen before beta v0.1.75 random[functionName](parameters); ``` This syntax is no longer supported in newer versions of Razen. ## Basic Examples ### Generating Random Integers ```razen # Import the random library lib random; # Generate a random integer between 1 and 10 (inclusive) num randomInt = random::int(1, 10); show "Random integer between 1 and 10: " + randomInt; # Generate a random integer between 1 and 100 num randomLarger = random::int(1, 100); show "Random integer between 1 and 100: " + randomLarger; # Generate a random integer with negative range num randomNegative = random::int(-10, 10); show "Random integer between -10 and 10: " + randomNegative; ``` ### Generating Random Floats ```razen # Import the random library lib random; # Generate a random float between 0 and 1 num randomFloat = random::float(0, 1); show "Random float between 0 and 1: " + randomFloat; # Generate a random float between 1.5 and 2.5 num randomDecimal = random::float(1.5, 2.5); show "Random float between 1.5 and 2.5: " + randomDecimal; # Generate a random percentage (0-100%) num randomPercentage = random::float(0, 100); show "Random percentage: " + randomPercentage + "%"; ``` ### Choosing Random Elements ```razen # Import the random library lib random; # Choose a random element from an array of strings str fruits = ["apple", "banana", "orange", "grape", "kiwi"]; str randomFruit = random::choice(fruits); show "Random fruit: " + randomFruit; # Choose a random element from an array of numbers num numbers = [10, 20, 30, 40, 50]; num randomNumber = random::choice(numbers); show "Random number: " + randomNumber; # Choose a random character from a string str word = "Razen"; str characters = []; for (num i = 0; i < word.length; i = i + 1) { characters.push(word[i]); } str randomChar = random::choice(characters); show "Random character from '" + word + "': " + randomChar; ``` ### Shuffling Arrays ```razen # Import the random library lib random; # Shuffle an array of numbers num numbers = [1, 2, 3, 4, 5]; show "Original array: " + numbers; num shuffledNumbers = random::shuffle(numbers); show "Shuffled array: " + shuffledNumbers; # Shuffle an array of strings str colors = ["red", "green", "blue", "yellow", "purple"]; show "Original colors: " + colors; str shuffledColors = random::shuffle(colors); show "Shuffled colors: " + shuffledColors; # Shuffle a deck of cards str suits = ["Hearts", "Diamonds", "Clubs", "Spades"]; str values = ["Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"]; str deck = []; # Create a deck of cards for (num i = 0; i < suits.length; i = i + 1) { for (num j = 0; j < values.length; j = j + 1) { deck.push(values[j] + " of " + suits[i]); } } show "Deck size: " + deck.length; str shuffledDeck = random::shuffle(deck); show "First 5 cards after shuffle: [" + shuffledDeck[0] + ", " + shuffledDeck[1] + ", " + shuffledDeck[2] + ", " + shuffledDeck[3] + ", " + shuffledDeck[4] + "]"; ``` ## Advanced Examples ### Random Password Generator ```razen # Import the random library lib random; # Function to generate a random password fun generatePassword(num length, bool includeUppercase, bool includeNumbers, bool includeSpecial) { # Define character sets str lowercase = "abcdefghijklmnopqrstuvwxyz"; str uppercase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; str numbers = "0123456789"; str special = "!@#$%^&*()-_=+[]{}|;:,.<>?"; # Create character pool based on options str charPool = lowercase; if (includeUppercase) { charPool = charPool + uppercase; } if (includeNumbers) { charPool = charPool + numbers; } if (includeSpecial) { charPool = charPool + special; } # Convert character pool to array str charArray = []; for (num i = 0; i < charPool.length; i = i + 1) { charArray.push(charPool[i]); } # Generate password str password = ""; for (num i = 0; i < length; i = i + 1) { password = password + random::choice(charArray); } return password; } # Generate passwords with different options show "Simple password (8 chars, lowercase only): " + generatePassword(8, false, false, false); show "Medium password (10 chars, with uppercase and numbers): " + generatePassword(10, true, true, false); show "Strong password (12 chars, with uppercase, numbers, and special chars): " + generatePassword(12, true, true, true); show "Very strong password (16 chars, all character types): " + generatePassword(16, true, true, true); ``` ### Random Color Generator ```razen # Import the random library lib random; # Function to generate a random RGB color fun randomRGBColor() { # Generate random values for red, green, and blue (0-255) num red = random::int(0, 255); num green = random::int(0, 255); num blue = random::int(0, 255); # Return as an array return [red, green, blue]; } # Function to generate a random hex color fun randomHexColor() { # Get random RGB values num rgb = randomRGBColor(); # Convert to hex str hexChars = "0123456789ABCDEF"; str hexColor = "#"; for (num i = 0; i < 3; i = i + 1) { num value = rgb[i]; num firstDigit = Math.floor(value / 16); num secondDigit = value % 16; hexColor = hexColor + hexChars[firstDigit] + hexChars[secondDigit]; } return hexColor; } # Generate random colors show "Random RGB Color: " + randomRGBColor(); show "Random Hex Color: " + randomHexColor(); # Generate multiple random hex colors show "Color Palette:"; for (num i = 0; i < 5; i = i + 1) { show "Color " + (i + 1) + ": " + randomHexColor(); } ``` ### Random Name Generator ```razen # Import the random library lib random; # Function to generate a random name fun generateRandomName() { # Arrays of first names and last names str firstNames = [ "James", "Mary", "John", "Patricia", "Robert", "Jennifer", "Michael", "Linda", "William", "Elizabeth", "David", "Barbara", "Richard", "Susan", "Joseph", "Jessica", "Thomas", "Sarah", "Charles", "Karen", "Christopher", "Nancy", "Daniel", "Lisa", "Matthew", "Margaret", "Anthony", "Betty", "Mark", "Sandra", "Donald", "Ashley", "Steven", "Dorothy", "Paul", "Kimberly", "Andrew", "Emily", "Joshua", "Donna" ]; str lastNames = [ "Smith", "Johnson", "Williams", "Jones", "Brown", "Davis", "Miller", "Wilson", "Moore", "Taylor", "Anderson", "Thomas", "Jackson", "White", "Harris", "Martin", "Thompson", "Garcia", "Martinez", "Robinson", "Clark", "Rodriguez", "Lewis", "Lee", "Walker", "Hall", "Allen", "Young", "Hernandez", "King", "Wright", "Lopez", "Hill", "Scott", "Green", "Adams", "Baker", "Gonzalez", "Nelson", "Carter" ]; # Choose random first and last names str firstName = random::choice(firstNames); str lastName = random::choice(lastNames); # Return full name return firstName + " " + lastName; } # Generate random names show "Random Name 1: " + generateRandomName(); show "Random Name 2: " + generateRandomName(); show "Random Name 3: " + generateRandomName(); # Generate a list of random names str randomNames = []; for (num i = 0; i < 5; i = i + 1) { randomNames.push(generateRandomName()); } show "List of Random Names:"; for (num i = 0; i < randomNames.length; i = i + 1) { show (i + 1) + ". " + randomNames[i]; } ``` ## Practical Application: Simple Dice Game ```razen # Import the random library lib random; # Simple dice game class class DiceGame { # Constructor init(num numDice) { this.numDice = numDice; this.playerScore = 0; this.computerScore = 0; this.roundNumber = 0; } # Roll dice fun rollDice(num count) { str results = []; num sum = 0; for (num i = 0; i < count; i = i + 1) { num roll = random::int(1, 6); results.push(roll); sum = sum + roll; } return { "rolls": results, "sum": sum }; } # Play a round fun playRound() { this.roundNumber = this.roundNumber + 1; show "=== Round " + this.roundNumber + " ==="; # Player's turn show "Player's turn:"; map playerRoll = this.rollDice(this.numDice); show "Player rolled: " + playerRoll["rolls"] + " (Sum: " + playerRoll["sum"] + ")"; # Computer's turn show "Computer's turn:"; map computerRoll = this.rollDice(this.numDice); show "Computer rolled: " + computerRoll["rolls"] + " (Sum: " + computerRoll["sum"] + ")"; # Determine winner of the round if (playerRoll["sum"] > computerRoll["sum"]) { show "Player wins this round!"; this.playerScore = this.playerScore + 1; } else if (computerRoll["sum"] > playerRoll["sum"]) { show "Computer wins this round!"; this.computerScore = this.computerScore + 1; } else { show "It's a tie!"; } # Show current score show "Current score - Player: " + this.playerScore + ", Computer: " + this.computerScore; show ""; } # Play multiple rounds fun playGame(num rounds) { show "Welcome to the Dice Game!"; show "Playing with " + this.numDice + " dice for " + rounds + " rounds."; show ""; for (num i = 0; i < rounds; i = i + 1) { this.playRound(); } # Show final results show "=== Game Over ==="; show "Final score - Player: " + this.playerScore + ", Computer: " + this.computerScore; if (this.playerScore > this.computerScore) { show "Player wins the game!"; } else if (this.computerScore > this.playerScore) { show "Computer wins the game!"; } else { show "The game ends in a tie!"; } } } # Create a new game with 2 dice DiceGame game = new DiceGame(2); # Play 3 rounds game.playGame(3); ``` ## Summary The Random Library in Razen provides essential functions for generating random values: - `int` for random integers within a range - `float` for random floating-point numbers within a range - `choice` for selecting random elements from arrays - `shuffle` for randomizing the order of array elements These functions help you add randomness to your Razen programs for games, simulations, and other applications that require unpredictable values.