Roll dice in python

Use Python to build a Dice Roller App

A simple step-by-step guide to building a Dice Rolling Simulator

I recently applied for a Data Science job and one of the requirements to submit the application was for me to copy and paste code into a small Indeed window… Something about the whole process seemed demeaning but I went through with it.

The prompt requested that I build a simple dice roller using whatever coding language I desired. Since Python is where I have done most of my learning, I naturally chose that. The IDE I’m using is Jupyter Notebook.
I went a little above and beyond and made a Graphical User Interface (GUI) for the dice roller and made it so you can pick the number of sides on the dice as well as the number of dice you want to roll because I like to challenge myself.

It’s a fun and simple little project so I decided to share how I went about it.

Creating the function

For this part of the project, I imported 2 libraries: statistics and randint (from random). The statistics library is not needed for this project, but I think it’s neat to use the library to gather statistics on any rolling you decide to do.

from random import randint
import statistics

Now we are ready to create our dice rolling function. For this function, there will be 2 required inputs: n and x.

Читайте также:  pop

n will be the number of sides for the dice you are rolling.
x will be the number of dice you are rolling.

# Define the dice rolling function using two inputs.
rolls = []
def roll_many(n, x):
for i in range(x):
roll = randint(1,n)
rolls.append(roll)
print(roll)

That’s it! Simple enough. Now you can use this function to obtain dice rolls.

# This cell will simulate rolling 2 six-sided dice.
rolls = []
roll_many(6,2)

Here is an example of what should show up when you run it:

And, as previously stated, you can use the statistics library to gather statistics on your dice rolls.

Here is an example of how you can use the statistics library to get statistics on your dice rolls:

Creating a GUI for the function

I had never tried to make my Python Code work in a GUI, so this part was new to me. After a little Google searching, I decided to use the tkinter library for this part of the project.

Because this part was newer to me, I decide to exclude rolling multiple dice and kept the rolling to a singular die for simplicity.

The next code snippet might seem a little convoluted for beginners. Here I am defining a window class. In the class, I am defining the different things that will appear in the window: an area to type in the number of sides on the die, a button to roll the die and all of the labels that designate what these areas are to the user by using text.

class MyWindow: 
def __init__(self, win):
self.lbl1=Label(win, text='# of Die Sides')
self.lbl2=Label(win, text='Roll Result')
self.lbl3=Label(win, text='Dice Rolling Simulator', font=("Helvetica", 20))
self.t1=Entry()
self.t2=Entry()
self.btn1 = Button(win, text='Roll Dice')
self.lbl1.place(x=100, y=100)
self.t1.place(x=200, y=100)
self.b1=Button(win, text='Roll Dice', font=("Helvetica", 16), command=self.roll)
self.b1.place(x=200, y=140)
self.b1.config(height=1, width=8)
self.lbl2.place(x=100, y=200)
self.t2.place(x=200, y=200)
self.lbl3.place(x=100, y=35)

Next, I define the roll function for the button. The roll function here, is very similar to the one we saw above, however there are a few additional lines so that the GUI will utilize the function.

def roll(self): 
self.t2.delete(0, 'end')
n=int(self.t1.get())
result=randint(1,n)
self.t2.insert(END, str(result))

Finally, I define the window using tkinter, I add a title (the name title of the window that appears in the top part) to the window as well as the dimensions and the position on the screen the window will appear. The window.mainloop() is an event listening loop, so that our app is ready to respond to new input.

window=Tk()
mywin=MyWindow(window)
window.title('Dice Roller')
window.geometry("400x300+10+10")
window.mainloop()

Altogether, the snippet looks like this:

from tkinter import *
class MyWindow:
def __init__(self, win):
self.lbl1=Label(win, text='# of Die Sides')
self.lbl2=Label(win, text='Roll Result')
self.lbl3=Label(win, text='Dice Rolling Simulator', font=("Helvetica", 20))
self.t1=Entry()
self.t2=Entry()
self.btn1 = Button(win, text='Roll Dice')
self.lbl1.place(x=100, y=100)
self.t1.place(x=200, y=100)
self.b1=Button(win, text='Roll Dice', font=("Helvetica", 16), command=self.roll)
self.b1.place(x=200, y=140)
self.b1.config(height=1, width=8)
self.lbl2.place(x=100, y=200)
self.t2.place(x=200, y=200)
self.lbl3.place(x=100, y=35)
def roll(self):
self.t2.delete(0, 'end')
n=int(self.t1.get())
result=randint(1,n)
self.t2.insert(END, str(result))
window=Tk()
mywin=MyWindow(window)
window.title('Dice Roller')
window.geometry("400x300+10+10")
window.mainloop()

And, after running the code…

Voilà! Let’s input a 20 for the # of Die Sides and see what we get:

Lucky number seven! It’s nothing fancy, but it’s a working Dice Rolling Simulator.

If you are having problems writing the code or just want to copy and paste the code so you have the Dice Rolling Simulator, here is the GitHub repository link:

Источник

simulating rolling 2 dice in Python

I have been asked to simulate rolling two fair dice with sides 1-6. So the possible outcomes are 2-12. my code is as follows:

def dice(n): x=random.randint(1,6) y=random.randint(1,6) for i in range(n): z=x+y return z 

My problem is that this is only returning the outcome of rolling the dice 1 time, so the outcome is always 2-12. I want it to return the sum of rolling the dice (n) times. Does anyone have any suggestions for me?

1 Answer 1

Roll the dice in the loop:

def dice(n): total = 0 for i in range(n): total += random.randint(1, 6) return total 

The += augmented assignment operator basically comes down to the same thing as total = total + random.randint(1, 6) when summing integers (it is slightly more complicated than that, but that only matters for mutable objects like lists).

def dice(n): return sum(random.randint(1, 6) for _ in range(n)) 

This basically does the same thing as the for loop in the first example; loop n times, summing up that many random numbers between 1 and 6 inclusive.

If instead of rolling n times, you need to produce n results of 2 dice rolls, you still need to roll in the loop, and you need to add the results to a list:

def dice(n): rolls = [] for i in range(n): two_dice = random.randint(1, 6) + random.randint(1, 6) rolls.append(two_dice) return rolls 

This too can be written out more compactly, with a list comprehension:

def dice(n): return [random.randint(1, 6) + random.randint(1, 6) for _ in range(n)] 

You could also use random.choice() from a list of generated sums; these are automatically weighted correctly; this basically pre-computes the 36 possible dice values (11 unique), each with equal probability:

from itertools import product two_dice_sums = [a + b for a, b in product(range(1, 7), repeat=2)] def dice(n): return [random.choice(two_dice_sums) for _ in range(n)] 

Either way, you’ll get a list with n results:

>>> dice(5) [10, 11, 6, 11, 4] >>> dice(10) [3, 7, 10, 3, 6, 6, 6, 11, 9, 3] 

You could pass the list to the print() function to have these printed on one line, or on separate lines:

>>> print(*dice(5)) 3 7 8 6 4 >>> print(*dice(5), sep='\n') 7 8 7 8 6 

Источник

Simulate rolling dice in Python?

now each time that I enter r it will generate the same number over and over again. I just want to change it each time. I would like it to change the number each time please help I asked my professor but this is what he told me.. «I guess you have to figure out» I mean i wish i could and i have gone through my notes over and over again but i don’t have anything on how to do it :-/ by the way this is how it show me the program

COP 1000 Let's play a game of Chicken! Your score so far is 0 Roll or Quit(r or q)r 1 r 1 r 1 r 1 

I would like to post an image but it won’t let me I just want to say THANK YOU to everyone that respond to my question! every single one of your answer was helpful! **thanks to you guys I will have my project done on time! THANK YOU

It seems like you’re missing some code here — you’d need some sort of loop to get the output you’re showing .

yes, I thought it was going to select a random number each time but it is not doing it. which makes me think it is the wrong code for it and the professor never taught us how to do it, maybe because there are people in the class that program before but this is my first time and not having the best experience, especially when he doesn’t even want to take the time to give me a hand and help me where i am stuck

5 Answers 5

import random dice = [1,2,3,4,5,6] #any sequence so it can be [1,2,3,4,5,6,7,8] etc print random.choice(dice) 
import random computer= 0 #Computer Score player= 0 #Player Score print("COP 1000 ") print("Let's play a game of Chicken!") print("Your score so far is", player) r= random.randint(1,8) # this only gets called once, so r is always one value print("Roll or Quit(r or q)") 

Your code has quite a few errors in it. This will only work once, as it is not in a loop. The improved code:

from random import randint computer, player, q, r = 0, 0, 'q', 'r' # multiple assignment print('COP 1000') # q and r are initialized to avoid user error, see the bottom description print("Let's play a game of Chicken!") player_input = '' # this has to be initialized for the loop while player_input != 'q': player_input = raw_input("Roll or quit ('r' or 'q')") if player_input == 'r': roll = randint(1, 8) print('Your roll is ' + str(roll)) # Whatever other code you want # I'm not sure how you are calculating computer/player score, so you can add that in here 

The while loop does everything under it (that is indented) until the statement becomes false. So, if the player inputted q , it would stop the loop, and go to the next part of the program. See: Python Loops — Tutorials Point

The picky part about Python 3 (assuming that’s what you are using) is the lack of raw_input . With input , whatever the user inputs gets evaluated as Python code. Therefore, the user HAS to input ‘q’ or ‘r’. However, a way to avoid an user error (if the player inputs simply q or r , without the quotes) is to initialize those variables with such values.

Источник

Оцените статью