lundi 22 octobre 2018

A paradox? Impossible outcome of a simple function?

I'm making a dice of the Royal Game of Ur in C#. It needs 4 4-sided pyramids that have 2 out of 4 peaks colored white. This means that a single dice gives 50/50 chance of being either 0 or 1.

Now look at this code and tell me why it sometimes gives me 5 and 6.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class ButtonScript : MonoBehaviour {
    public Button rollButton;
    public int result;

    void Start()
    {
        rollButton.onClick.AddListener(onClick);
    }

    void resultReset()
    {
        Debug.Log("Setting result from " + result + " to 0");
        result = 0;
    }

    public int Calculate()
    {        
        for (int i = 0; i < 4; i++)
        {
            int num = Random.Range(0,2); // Either 1 or 0.

            result = result + num; // num is added to total result
            if (result > 4)
            {
                Debug.Log("Rolling " + result + " not possible!!");
            }
        }
        return result;
    }

    void onClick()
    {
        resultReset();

        int iRolled = Calculate();
        Debug.Log("I rolled " + iRolled); // Sometimes gives 5+ and skips the for loop (like, goes 1-2 times and gives out an impossible number)
    }

}




Aucun commentaire:

Enregistrer un commentaire