---
description: Weighted random values give you more influence over outcomes and rarity
---

# Weighted Random Chance (WRC)

## What is a Weighted Random?

### Overview

A weighted random is a method of selecting random numbers where each possible outcome is assigned a probability weight. Unlike true random selection, where every outcome has an equal chance of being selected, weighted randomization alters these chances based on the weights. This means that some outcomes are more likely to occur than others, depending on their assigned weights.

COZY uses weighted random numbers for many functions. Weather forecasting, ambience selection, [Color Block selection](modules/blocks-module) and more are all done using the power of this psuedo-random functionality.

### Advantages of Weighted Random in COZY

Weighted random selection offers several benefits when implemented in applications like COZY:

* **Tailored Experience**: By adjusting the weights, COZY can tailor the user experience. For example, more favorable weather conditions can be made more likely in a forecast, enhancing user satisfaction.
* **Dynamic Adjustment**: The system can dynamically adjust the weights based on user feedback or preferences. If users enjoy a specific Color Block or ambience more, these can be programmed to appear more frequently.
* **Creativity and Variety**: Using weighted random allows COZY to introduce a creative and varied experience each time. It ensures that the app remains fresh and engaging by occasionally introducing less common outcomes.

## Weighted Random Variables

Anywhere that a pseudo-random value is used, there are a few variables that you will always be able to tweak.

### Likelihood or Chance

This is the base chance of this outcome. In a standard random function each outcome has a chance of 1 meaning that each outcome is equally likely. A chart of the ratio of outcomes will look approximately like this:

|                      <mark style="background-color:purple;">Rainy</mark>                        |                         <mark style="background-color:green;">Cloudy</mark>                       |                        <mark style="background-color:orange;">Sunny</mark>                                                            |
| :---------------------------------------------------------------------------------------------: | :-----------------------------------------------------------------------------------------------: | :-----------------------------------------------------------------------------------------------------------------------------------: |

While the next number is always random, by the end of the rolls there will be about the same number of each possible outcome.

If you were to set an outcome (such as sunny) to have a chance of 2, this drastically changes the outcome set. Now that outcome has a higher chance of occurring and will be twice as likely as the other outcomes. Now our chart looks like this:

<table data-header-hidden data-full-width="false"><thead><tr><th width="161" align="center"></th><th width="203" align="center"></th><th align="center"></th></tr></thead><tbody><tr><td align="center">        <mark style="background-color:purple;">Rainy</mark>              </td><td align="center">                 <mark style="background-color:green;">Cloudy</mark>                 </td><td align="center">                                        <mark style="background-color:orange;">Sunny</mark>                                          </td></tr></tbody></table>

### Chance Effectors

While that helps to make certain weather types more rare than others, it does not necessarily reflect the real world. In the real world, the weather forecast has many factors that contribute to what happens outside our windows such as temperature, humidity, etc. This is reflected in COZY through the use of **chance effectors**. Chance effectors function as multipliers for our base chance by taking in a variable, charting it on a curve and outputting a multiplier

<figure><img src="https://2041269432-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FrqKsGNTyQFMrNJSWMHS0%2Fuploads%2FdaRPVlfN2ma3YQKWJFYp%2Fimage.png?alt=media&#x26;token=61bba315-ff94-4b43-b2f5-962e1f4d9cee" alt=""><figcaption></figcaption></figure>

In our simulation, there are several variables that we can choose from to change our base chance.

* Temperature
* Precipitation
* Year percentage
* Time
* Accumulated Wetness
* Accumulated Snow

These values each have their own preset multiplier curves for quick editing. Select a preset curve by hitting the dropdown button on the right.

<figure><img src="https://2041269432-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FrqKsGNTyQFMrNJSWMHS0%2Fuploads%2Fwleue8CBuQPuV4OqfD6d%2Fimage.png?alt=media&#x26;token=2336d58e-825a-4484-8d03-82eb150c9fad" alt=""><figcaption></figcaption></figure>

### How Does it Work?

Bringing the chart back from earlier, chance effectors work by multiplying the chance based on the curve. Let's say that the weather profile "Sunny" has a chance effector curve that increases the likelihood at high temperatures and another that lowers the likelihood when the precipitation is high. The weather profile "Rainy" has a chance effector curve that increases the likelihood when the precipitation is high.

Now we can look at how the likelihood changes depending on the current settings of COZY.

> Temperature: 85°
>
> Precipitation: 15%

<table data-header-hidden><thead><tr><th width="46" align="center"></th><th width="230" align="center"></th><th align="center"></th></tr></thead><tbody><tr><td align="center">   </td><td align="center">                    <mark style="background-color:green;">Cloudy</mark>                     </td><td align="center">                                                  <mark style="background-color:orange;">Sunny</mark>                                                           </td></tr></tbody></table>

The chance that it will rain has dropped to 0 for now and it is very likely that the sun will come out. However as the day goes on and these values change, the chances change as well.

> Temperature: 60°
>
> Precipitation: 80%

<table data-header-hidden><thead><tr><th width="380" align="center"></th><th width="207" align="center"></th><th align="center"></th></tr></thead><tbody><tr><td align="center">                                    <mark style="background-color:purple;">Rainy</mark>                                          </td><td align="center">                <mark style="background-color:green;">Cloudy</mark>                   </td><td align="center">            <mark style="background-color:orange;">Sunny</mark>                                                           </td></tr></tbody></table>

Now the chance of rain is much higher. This not only makes our weather more believable, but also makes these variables more than just cosmetic; they actually change the weather.

## API

### Custom WRC Tutorial

As of COZY 3.4.0 you are now able to create your own custom WRC values that can be extended with profiles. In this tutorial, we will make a WRC that increases the chance of a weather as the game time increases. This is useful for giving grace periods before heavy rain starts.

#### Step 1: Create the WRC script

Create a new C# script and name it GameTimeChanceEffector.cs. Now paste this code into the script:

```csharp
using System;
using UnityEngine;

namespace DistantLands.Cozy
{
    [Serializable]
    [CreateAssetMenu(menuName = "Distant Lands/Cozy/WRC/Game Time Chance", order = 361)]
    public class GameTimeChanceEffector: CustomCozyChanceEffector
    {
        public float chance;
        public override float GetChance()
        {
            return chance;
        }
    }
}
```

This code is a simple WRC that you can use as a base to build your own. From this we only need to make a few changes to implement some custom logic.

```csharp
using System;
using UnityEngine;

namespace DistantLands.Cozy
{
    [Serializable]
    [CreateAssetMenu(menuName = "Distant Lands/Cozy/WRC/Game Time Chance", order = 361)]
    public class GameTimeChanceEffector: CustomCozyChanceEffector
    {
        public float totalTimeInSeconds = 60f; // Total time in seconds
        
        public override float GetChance()
        {
            float elapsedTime = Time.time; // Get the time elapsed since the game started
            return Mathf.Clamp01(elapsedTime / totalTimeInSeconds); // Clamps the chance from 0 - 1
        }
    }
}
```

#### Step 2: Create a WRC profile

Now in your Unity project right click in the project window and select `Create/Distant Lands/Cozy/WRC/Game Time Chance`. This will create a new WRC asset in your project.

#### Step 3: Assign your WRC

In your weather profile, add a new chance effector to the list of chance effectors and set the type to custom. Now assign the WRC profile that you just created here.
