Home > database >  Creating a program that simulates dice rolling
Creating a program that simulates dice rolling

Time:10-17

I am trying to create a program in python that simulates dice rolling. I have not got much code but I do not know how to begin on creating the code for "previous_roll". This is made so that the previous roll is returned in the function so the next number that is generated is different than the one that was given before. This is the code I have so far.

import random

def roll_dice(previous_roll):
    return random.randint(start,end)

random_number = roll_dice(previous_roll)
print(random_number)

I know that this is incomplete, I just do not know what to do with the previous roll parameters.

CodePudding user response:

Roll it twice, then check if its the same, if it is, then reroll it.

import random

def roll_dice():
    dice1 = random.randint(1,6)
    dice2 = random.randint(1,6)
    while dice1 == dice2:
        dice2 = random.randint(1,6)
    return dice1, dice2

CodePudding user response:

import numpy as np


def roll_dice(previous_roll: int, start_num: int, end_num: int) -> int:
    """random dice rolling excluding previous roll
    :parameter
        - previous_roll:
          number that was previously rolled
        - start_num:
          start of all possible numbers
        - end_num
          end of all possible numbers (needs to be n 1 if n should be possible)
    :return
        - new_choice
          result of the dice roll
    """
    # ndarray with all possible numbers that can be rolled
    all_choice = np.arange(start_num, end_num)
    # ndarray with all possible numbers except the previous_roll
    pos_choices = all_choice[all_choice != previous_roll]
    # new random chosen number
    new_choice = np.random.choice(pos_choices)
    return new_choice

This eliminates the need of a for/while loop which can become very inefficient.

  • Related